Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

errors in a loop

Given the following loop on each element of a list:

lists:foldl(fun(X) -> ... end,N,Y),

How to catch the errors and continue to loop on the elements ?

Same question if this code is in a gen_server and if process_flag(trap_exit, true) ?

like image 666
Bertaud Avatar asked Feb 03 '26 22:02

Bertaud


1 Answers

Why you just can't use try/catch like this?

1> lists:foldl(
1>     fun (E, A) ->
1>         try E + A
1>         catch
1>             _:_ ->
1>                 A
1>         end
1>      end, 0, [1, 2, 3, 4, a, 6]).
16

Or you can use a decorator function if you want to extract error handling, like this:

1> Sum = fun (E, A) -> E + A end.
#Fun<erl_eval.12.113037538>
2> HandlerFactory = fun (F) ->              
2>     fun (E, A) ->
2>         try F(E, A)
2>         catch
2>             _:_ ->
2>                 A
2>         end
2>     end
2> end.
#Fun<erl_eval.6.13229925>
3> lists:foldl(HandlerFactory(Sum), 0, [1, 2, 3, 4, a, 6]).
16
4> Mul = fun (E, A) -> E * A end.
#Fun<erl_eval.12.113037538>
5> lists:foldl(HandlerFactory(Mul), 1, [1, 2, 3, 4, a, 6]).
144
like image 80
hdima Avatar answered Feb 05 '26 14:02

hdima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!