gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:12:52 25 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改进这个问题?更新问题,以便 editing this post 提供事实和引用来回答它.

8年前关闭。




Improve this question




哪个更安全、更好、更清洁、更推荐使用?

我用了:

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 更好?

我的问题是:你会怎么写这个,你为什么会选择那种方式?

最佳答案

更新
感谢一位匿名用户,我已经能够纠正我的答案中的错误。 returncatch block 没有达到预期的效果,因为它只从 catch 返回子程序。
如果没有异常(exception),try返回 try 的值 block ,否则 catch 的值堵塞。所以这个版本正确执行并返回$c->redirect("/index")的值如果 insert成功,否则调用并返回$c->show_error($_)的值.

sub insert_exec {
my ($self, $c, $args) = @_;
my ($params, $table, $model) = $self->_init({context => $c, 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, $c, $args) = @_;
my ($params, $table, $model) = $self->_init({context => $c, args => $args});
try {
$model->insert($table, $params);
}
catch {
return $c->show_error($_);
};
$c->redirect("/index");
}
我希望你会同意更好。
有两点值得注意:
  • trycatch是编码成看起来像语言单词的子程序。这意味着最后一个右大括号后的分号是必不可少的。
  • 出于同样的原因,returntry 内或 catch block 不会按预期工作,并且会简单地退出 block ,返回父子程序。请参阅上面的更新。
  • catch block $@具有 try 之前的原始值.错误产生的值在$_
  • 关于perl - 使用 Try::Tiny 还是 Eval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18013474/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com