我用了:
sub insert_exec { my ($self,$c,$args) = @_; my ($params,$table,$model) = $self->_init({context => $c,args => $args}); eval { $model->insert($table,$params); }; if ($@) { return $c->show_error($@); } ## error $c->redirect("/index"); }
但是对于这种情况(参见错误部分),我被告知使用Try :: Tiny更好吗?
我的问题是:你会怎么写这个,为什么你会这样选择?
解决方法
感谢匿名用户,我已经能够纠正我的答案中的错误. catch块中的返回没有达到预期的效果,因为它只从catch子例程返回.
如果没有异常,则尝试返回try块的值,否则返回catch块的值.因此,如果插入成功,此版本正确执行并返回$c-> redirect(“/ index”)的值,否则它将调用并返回$c-> show_error($_)的值.
sub insert_exec { my ($self,$args) = @_; my ($params,args => $args}); try { $model->insert($table,$params); $c->redirect("/index"); } catch { $c->show_error($_); }; }
Try::Tiny
非常重要,因为在一般情况下,使用eval进行错误处理非常困难.该模块的文档说明了这一点
This module provides bare bones try/catch/finally statements that are designed to minimize common mistakes with eval blocks,and nothing else.
The main focus of this module is to provide simple and reliable error handling for those … who still want to write correct eval blocks without 5 lines of boilerplate each time.
你的代码看起来像这样
use Try::Tiny; sub insert_exec { my ($self,$params); } catch { return $c->show_error($_); }; $c->redirect("/index"); }
我希望你会同意的更好.
有两点值得注意:
> try和catch是编码为语言单词的子程序.这意味着在最后的闭合支撑后必须使用分号.>出于同样的原因,try或catch块中的返回将无法按预期工作,并且只是退出块,返回到父子例程.请参阅上面的更新.>在catch块中,$@在尝试之前具有其原始值.错误产生的值是$_
原文地址:https://www.jb51.cc/Perl/171910.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。