erlang mnesia - illegal record info

hyp*_*ean 5 erlang mnesia record

I am trying to have a function that ensures the table I need is already created and if not to create it. Here's the sample:

ensure_table_exists(Table, MnesiaTables, Nodes) ->
case lists:member(Table, MnesiaTables) of
    true ->
        throw({error, db_might_have_already_been_created});
    false ->
        mnesia:create_table(Table, [{disc_copies, Nodes},
                {attributes, record_info(fields, Table)}]), 
        ok  
end.
Run Code Online (Sandbox Code Playgroud)

The issue is that when compiling I get the error: illegal record info. It might have to do that record_info is resolved at compile time or that the second argument to record info should actually be a record that can be retrieved from the source code ?

rvi*_*ing 5

是的,所有的记录相关的东西,包括record_info/2在编译时解决。这意味着在编译时必须知道记录和字段名称。这就是编译器错误的原因。

我不认为您的功能真的太具有防御性,因为您正在做的是发出更具体的错误信号。如果你要回来, 那就是另一回事了{error, ...}

最后一点是,如果您想引发异常,则不应使用throw/1,而应使用erlang:error/1. throw用于非本地返回(带有catch),而erlang:error用于引发异常。在许多情况下,结果可能相同,但实际误差值可能具有误导性 ( nocatch)。您能更清楚地表明您的意图总是更好,在这种情况下,这是一个错误信号。

PS 是的,我知道catch也会捕获错误/退出。这是故意的。在一个完美的世界中,也许catch应该只捕获抛出和try错误/退出。


Rob*_*loi 0

您可能想看看Ulf Wiger 的exprecs

从描述中读取:

该模块是一个解析转换,允许您导出记录。该转换添加了用于实例化、检查和修改记录的访问器函数,而无需在模块之间引入编译时依赖关系。

这么说来,你的功能对我来说听起来有点防御性。下一页解释了为什么在 Erlang 中进行防御性编程是一个坏习惯:

http://www.erlang.se/doc/programming_rules.shtml#HDR11