Cycle errors

Given the following loop for each list item:

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

How to catch errors and continue to cycle through the elements?

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

+3
source share
2 answers

Why can't you just 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 the decorator function if you want to extract error handling, for example:

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
+3
source

The first sentence from @hdima is the simplest and gives you complete control over how to handle various errors / throws, etc. For example, you can allow throwing as a form of nonlocal exit from foldl. Are you really sure you want to ignore errors?

HandlerFactory, OO, .:-) .

gen_server, . , , try. trap_exit , , receive, .

0

Source: https://habr.com/ru/post/1788840/


All Articles