I come from a Java and Ruby background and I was wondering if there is any equivalent of "method_missing" in Erlang. I have looked at the documentation and the closest I can see is the use of erl_eval and erl_parse, but I wanted to know if there is any other way?
There is the 'error_handler' module which is called when you attempt to call an undefined function.
process_flag(error_handler, Module).
The module needs to export undefined_function/3 and undefined_lambda/3. You can see how this should be implemented in the standard handler module, error_handler.
You need to be careful in your own error_handler not to break the standard code loading system. Erlang usually tries to load the module from an undefined function error and re-run the function before giving up and signalling an error. You usually want to try the standard error_handler first and fall back to your new behaviour if that fails.
archaelus pointed in a good direction, but if you prefer not to meddle with the error_handler, it does support a nice callback routine notifying the module being called that there was an attempt to call an undefined function, which seems quite handy.
https://github.com/erlang/otp/blob/maint/lib/kernel/src/error_handler.erl#L139
So if you add this in a module:
'$handle_undefined_function'(Func, Args) ->
io:format("Called undefined function '~p' with args ~p.~n", [Func, Args]).
It'll print out a message whenever a call is made to a undefined function in that module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With