A similar question was asked about this but it was not exactly asked in the same terms.
I am trying to safely decode base64 binaries, in a context where it's possible the input will not be a binary, or even base64 encoded.
Erlang says let it crash and handle it -- if I were to do this, what is the most efficient way. Efficiency is quite important in this system.
I know to avoid try/catch, as it builds a full stack trace -- however, is the catch keyword reasonable for this context? And is the catch keyword faster/more efficient?
In a function such as
safe_decode(Binary) ->
case catch base64:decode(Binary) of
<<Result/binary>> -> {ok, Result};
{'EXIT', _} -> {not_base64, Binary}
end.
Is this truly more efficient than a try catch? How best to handle this scenario in a system where efficiency is important i.e. crashes which involve building a stack trace and/or require more processing than the happy path need to be handled as efficiently as possible.
I'm just learning erlang, so maybe the answer is staring me in the face.
spawn_monitor
a painlessly crashable process that will either send you a message of success or a death note (the monitor) on failure straight away without encouraging anytry..catch
madness. Sometimes this is the ideal solution. Sometimes not. As always, benchmark. If you are catching a lot of bad input data then the crashes may be a lighter load. If 99% of your input data is good, thentry..catch
is probably better. – Jalousie