EEP 36: Line numbers in exceptions

最近关于Erlang程序在异常打印堆栈时候带上行号信息的提案开始被讨论了,具体看这里:
EEP 36: Line numbers in exceptions: http://www.erlang.org/eeps/eep-0036.html

初学Erlang的人估计都有这个困惑,程序异常的时候打印堆栈不假,但是只打出函数名,如果模块很长的话,很难找到具体发生异常的点,通常再通过 打日志的方式来定位,非常的低效无聊。有人开玩笑说是Erlang鼓励写短函数和模块. 我曾经想了个方法解决这个问题, 见 这里 , 但不是完美的方案。

EEP 36则是从编译器直接搞定这个问题,会爽很多, 我们看下他的效果:

-module(example).
-export([m/1]).
-include("header.hrl").
 
m(L) ->
    {ok,lists:map(fun f/1, L)}.  %Line 6
 
%%and the header file header.hrl:
 
f(X) ->
    abs(X) + 1.        %Line 2
 
%%Using R14B01 to call our example module, we get the following result:
 

1> example:m([-1,0,1,2]).

{ok,[2,1,2,3]}

2> example:m([-1,0,1,2,not_a_number]).

** exception error: bad argument

     in function  abs/1

        called as abs(not_a_number)

     in call from example:f/1

     in call from lists:map/2

     in call from lists:map/2

     in call from example:m/1

3> catch example:m([-1,0,1,2,not_a_number]).

{'EXIT',{badarg,[{erlang,abs,[not_a_number]},

                 {example,f,1},

                 {lists,map,2},

                 {lists,map,2},

                 {example,m,1},

                 {erl_eval,do_apply,5},

                 {erl_eval,expr,5},

                 {shell,exprs,7}]}}

1> example:m([-1,0,1,2]).            

{ok,[2,1,2,3]}

2> example:m([-1,0,1,2,not_a_number]).

** exception error: bad argument

     in function  abs/1

        called as abs(not_a_number)

     in call from example:f/1 (header.hrl, line 2)

     in call from lists:map/2 (lists.erl, line 948)

     in call from lists:map/2 (lists.erl, line 948)

     in call from example:m/1 (example.erl, line 6)

3> catch example:m([-1,0,1,2,not_a_number]).

{'EXIT',{badarg,[{erlang,abs,[not_a_number],[]},

                 {example,f,1,[{file,"header.hrl"},{line,2}]},

                 {lists,map,2,[{file,"lists.erl"},{line,948}]},

                 {lists,map,2,[{file,"lists.erl"},{line,948}]},

                 {example,m,1,[{file,"example.erl"},{line,6}]},

                 {erl_eval,do_apply,5,[{file,"erl_eval.erl"},{line,482}]},

                 {erl_eval,expr,5,[{file,"erl_eval.erl"},{line,276}]},

                 {shell,exprs,7,[{file,"shell.erl"},{line,666}]}]}}

希望早日能用上这个功能。

玩得开心!

转载请注明:《EEP 36: Line numbers in exceptions