Comment

Comment by jcizzle

Great article, very much appreciate this guy and his blog as I continue to learn Erlang.

A question: the pattern of let it crash makes sense to me. However, I struggle with it when implementing RESTful web services. Letting the process crash will typically yield a 500 - the monitor on the connection process in the web server library ensures that. Clearly though, a status code and some additional information is a more appropriate response to the client. An example is returning a 400 for "missing arguments". In a contrived example of idiomatic Erlang, I feel like I'd write this:

    handle_request(Request) ->
        % username and password are required
        {ok, Username} = request:get_argument(<<"username">>, Request),
        {ok, Password} = request:get_argument(<<"password">>, Request),

        UserRecord = db:find(my_database, users, #{<<"username">> => Username}),
 
        Password = maps:get(<<"password">>, UserRecord),

        request:respond(200, UserRecord, Request).
And if the key username did not exist in Request, request:get_argument/2 would return undefined or {error, Reason}, giving me a bad match error. Or if the password didn't match, I'd get the same. In order to intercept that and return a reasonable status code, I would have to catch that in handle_request. My question, then, is am I missing a best practice on how to handle this? Or is this just the place where I do need to catch errors and process them? And if that is so, isn't it at odds with the whole concept of writing intentional code?
parent jcizzle 12 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton