How do you do error handling in Erlang? |
The inter-process part certainly is. As for intra-proces error handling, it’s basically the same as in other modern languages: you can signal errors with special return values, or you can throw exceptions. |
In typed languages, common special return values are |
In Erlang, which is dynamically-typed and symbolic, you typically
use an “error tuple”.
I.e. |
— then you’d probably add it like this: |
Well, no. Typically you wouldn’t do that — because the custom is to
expect a 2-tuple, to catch it with the pattern |
Ah, right. So you’d say Anything else to be aware of? |
You certainly shouldn’t pair just anything with case file:open(FileName, Modes) of %% open() returns {ok,_} | {error,_} {ok, Fd} -> something_good(Fd); Error -> {error, Error} end. That would result in a value like |
You do get to know a measure of how many levels deep the original error were, though… |
Yes, but it is still debatable whether it’s better or worse than nothing. |
So instead, I should just return |
Yes; either that or tag it anew with something providing a bit of context: {error,_}=Error -> Error %% or: {error,Reason} -> {error, {opening_the_foo_file_failed, Reason}} %% or, if you want to add details: {error,Reason} -> {error, {opening_the_foo_file_failed, Reason, Filename}} That way, the error message will tell not only what went wrong (``file not found``), but also what the program was trying to do at the time — a description at a higher level. |