otp icon indicating copy to clipboard operation
otp copied to clipboard

Documentation on early return from gen_server callbacks using throw

Open sanzor opened this issue 2 years ago • 2 comments

Could you please add documentation on how to early return from gen_server callbacks using throw ? I found this to be a neat way when dealing with multiple checks before actually processing a request 👍

-module(some_module).
-behaviour(gen_server).
-export([handle_call/3]).

handle_call(Request,From,State)->
   check1(Request,State),
   check2(Request,State),
   do_call(Request,From,State).

do_call(some_request,From,State)->
   {reply,{ok,some_ok_result},State};
do_call(some_other_request ,From,State)->
   {reply,{ok,some_ok_result},State};
do_call(Request,From,State)->
   {reply,{ok,3,State}.

check1(Request,State)->
   case condition1() of
        1 -> ok;
       WrongResult ->throw({reply,some_wrong_result,State);
   end.
    

check2(Request,State)
  case condition2() of
        3 -> ok;
       WrongResult ->throw({reply,some_other_wrong_result,State);
   end.


In the above code i have to do multiple checks on any request i am receiving before actually processing the request. Throw comes in handy to do some sort of pipeline where each check condition fails fast (stops the flow) and returns without crashing the server. I am throwing with a suitable reply in each of my checks.

Could you please add documentation to this , since i find it very very useful .

sanzor avatar Nov 26 '21 12:11 sanzor

Pull requests are accepted, also for documentation, and are, for documentation, fairly easily approved.

In the documentation for gen_statem I think there is an explicit mention somewhere about using throw/1 to return from a callback...

RaimoNiskanen avatar Nov 30 '21 14:11 RaimoNiskanen

Proposal in https://github.com/erlang/otp/pull/6053. Not sure how to get them properly linked.

bucko909 avatar Jun 06 '22 10:06 bucko909