Error Handling with Sockets

Error handling with sockets is extremely easy—basically you don’t have to do anything. As we said earlier, each socket has a controlling process (that is, the process that created the socket). If the controlling process dies, then the socket will be automatically closed.

This means that if we have, for example, a client and a server and the server dies because of a programming error, the socket owned by the server will be automatically closed, and the client will be sent a {tcp_closed, Socket} message.

We can test this mechanism with the following small program:

socket_examples.erl
 
error_test() ->
 
spawn​(​fun​() -> error_test_server() ​end​),
 
lib_misc:sleep(2000),
 
{ok,Socket} = gen_tcp:connect(​"localhost" ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.