加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 使用Try :: Tiny还是Eval?

发布时间:2020-12-15 21:54:39 所属栏目:大数据 来源:网络整理
导读:哪个更安全更好的清洁与清洁更推荐使用? 我用了: 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($@);
哪个更安全&更好的&清洁与清洁更推荐使用?

我用了:

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块中,$@在尝试之前具有其原始值.错误产生的值是$_

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读