erlangerlang-otpgen-servererlang-shell

Is there an option available for adding conditions in gen server?


Thanks for looking at the question and It would be helpful and appreciated if you guys can solve my question. Now here's my question..

I created a gen server in erlang for banking purposes and I just made it for deposit and withdraw. It's working perfectly fine and what I need now is to add conditions to the withdraw. Such as, if the amount to be withdrawn is going to make the balance below 100, then the withdraw has to be aborted and a display message such as "Minimum balance is 100" has to be shown. I am self learning and this is for my curiosity in how the gen server works with conditions. here's the part where the withdraw is happening.

deallocate(Available,M) ->
    New_state1 = Available - M,
    io:format("Amount withdrawn : ~p~n",[M]),
    io:format("Total Balance : ~p~n",[New_state1]),
    Reply = withdrawn,
    {New_state1,Reply}.

As you can see from the above lines, this is where the withdrawn is done. Now I am stuck here with where and how I can add conditions.

Any help is much appreciated and Thanks in advance even for trying. Good day!!


Solution

  • I'm gonna assume that you're calling this deallocate/2 function from within handle_call/3 and that the reply is given back to the caller, something like…

    handle_call({deallocate, M}, _From, State) ->
        {NewState, Reply} = deallocate(State, M),
        {reply, Reply, NewState};
    …
    

    If that's the case, you just need to return an error message to the client instead of withdrawn

    deallocate(Available,M) ->
        case Available - M of
            NewState when NewState < 100 ->
                {Available, {error, balance_under_minimum}};
            NewState ->
                io:format("Amount withdrawn : ~p~n",[M]),
                io:format("Total Balance : ~p~n",[NewState]),
                {NewState, withdrawn}
        end.
    

    Of course, on the client side you will have to understand the error message, so instead of…

    deallocate(M) -> gen_server:call(the_bank, {deallocate, M}).
    

    …you would do…

    deallocate(M) ->
        case gen_server:call(the_bank, {deallocate, M}) of
            withdrawn -> withdrawn;
            {error, balance_under_minimum} ->
                io:format("Minimum balance is 100\n"),
                not_withdrawn
        end.