[英]How to catch base exception class in Ruby on Rails?
I'd like to catch any RoR exceptions in REST API application with 'rescue_from'. 我想使用“ rescue_from”捕获REST API应用程序中的所有RoR异常。
rescue_from StandardError do |exception|
message = Rails.env.production? ? 'API server error' : exception.message
render json: {status: "Error", message: message}, status: :internal_server_error
end
but it catches too much irrelevant exceptions. 但是它捕获了太多无关的异常。 Can I catch RoR exceptions only?
我可以仅捕获RoR例外吗? Is it a good practice at all?
真的是个好习惯吗? If not, what else you can recommend?
如果没有,您还能推荐什么?
Well, you can always go out and get an exhaustive list of all the Rails exceptions, but honestly your first step should be to decide what situations you want to rescue from and which you want to allow to behave catastrophically. 好吧,您总是可以外出并获得所有Rails例外的详尽列表,但是老实说,您的第一步应该是确定要从中拯救的情况以及允许发生灾难性行为的情况。 Not all exceptions should be caught.
并非所有异常都应该被捕获。
If you're dead set on catching all Rails exceptions you should go look at the api documentation for the version of rails you're on and find the base classes for the exceptions you care about. 如果您对捕获所有Rails异常一无所知,则应该查看api文档以获取所使用的Rails的版本,并找到所需的异常的基类。 For example, if you're hoping to just catch all ActiveRecord ones, you can rescue from the base ActiveRecord::ActiveRecordError class.
例如,如果希望只捕获所有ActiveRecord的对象,则可以从ActiveRecord :: ActiveRecordError基类中进行救援。
Again, I'd stress that you should be approaching this from the other direction--not rescuing everything and then trying to thin it out, but by rescuing from the bare minimum and adding as needed. 同样,我要强调的是,您应该从另一个方向着手解决这个问题-不要抢救一切,然后尝试精打细算,而应从最低限度中抢救出来,并根据需要添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.