[英]Best way to do a rescue block
Is this the correct way to do a rescue in a block? 这是在街区进行救援的正确方法吗?
Also, is it the shortest? 另外,它最短吗?
def rescue_definition
begin
user.begin_rescue
rescue Example::ParameterValidationError => e
redirect_to :back, error: e.message_to_purchaser
rescue Example::ProcessingError => e
redirect_to :back, error: e.message_to_purchaser
rescue Example::Error
redirect_to :back, error: e.message_to_purchaser
else
if user
flash['success'] = 'OK'
else
flash['error'] = 'NO'
end
end
redirect_to :back
end
The idea to use begin, rescue, ensure is to put the methods than can generate an error in the begin
block, then you can handle the errors in one o more rescue
blocks and finally you can put an optional ensure
block for sentences that you want to execute on both success or fail scenarios for example release resources. 使用begin,rescue,suresure的想法是将可能产生错误的方法放在begin
块中,然后可以在一个或多个rescue
块中处理错误,最后可以为想要的句子放置一个可选的ensure
块。在成功或失败方案上执行,例如释放资源。
When you want all the method be handled by begin, rescue, ensure blocks, then begin
keyword is optional, you can use or not the keyword, since you are asking for the shortest option, you will need to do some minor changes to your code: 如果您希望所有方法都由begin,rescue,确保blocks处理,然后begin
关键字是可选的,则可以使用也可以不使用该关键字,因为您要求的是最短的选项,因此您需要对代码进行一些小的更改:
def rescue_definition
user.begin_rescue
# and any other stuff you want to execute
if user
flash['success'] = 'OK'
else
flash['error'] = 'NO'
end
redirect_to :back
rescue Example::ParameterValidationError => e
redirect_to :back, error: e.message_to_purchaser
rescue Example::ProcessingError => e
redirect_to :back, error: e.message_to_purchaser
rescue Example::Error
redirect_to :back, error: e.message_to_purchaser
end
If you want it even shorter you can rescue multiple exception types in one rescue block: 如果您希望它更短,则可以在一个救援块中救援多种异常类型:
def rescue_definition
user.begin_rescue
# and any other stuff you want to execute
if user
flash['success'] = 'OK'
else
flash['error'] = 'NO'
end
redirect_to :back
rescue Example::ParameterValidationError, Example::ProcessingError, Example::Error => e
redirect_to :back, error: e.message_to_purchaser
end
Aguar's post handles the current implementation. Aguar的帖子处理了当前的实现。 If you handle all the errors the same way then you can have them inherit from a custom class and just catch them all with 1 rescue call. 如果您以相同的方式处理所有错误,则可以让它们从自定义类继承,并通过1个抢救电话将其全部捕获。
def stuff
user.stuff
if user
flash['success'] = 'Ya'
else
flash['error'] = 'Nah'
end
redirect_to ....
rescue CustomClassError => e
redirect_to :back, error: e.message_to_purchaser
rescue NonCustomErrors => e
#handle it
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.