简体   繁体   English

如何在Ruby on Rails中捕获基本异常类?

[英]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.

相关问题 在Rails中为基本的ruby类添加方法 - Adding methods to base ruby class in rails 如何在Ruby中捕获和忽略ActiveRecord :: RecordNotUnique异常 - How to catch and ignore ActiveRecord::RecordNotUnique exception in Ruby 如何通过更改基类将Ruby / Rails方法包装在子类中? - How to wrap a Ruby/Rails method in a sub-class by altering the base class? 如何在Rails 2.3.8中捕获故障安全异常 - How to catch a failsafe exception in rails 2.3.8 Sidekiq/Rails:如何捕获异常并重试 - Sidekiq/Rails: How to catch exception AND retry 如果在 Rails 上使用 Ruby,如何为 2 个网站使用 1 个代码库以使 HTML 元素的 ID 和 class 名称不同? - If using Ruby on Rails, how to use 1 code base for 2 websites for the HTML elements' IDs and class names to be different? 如何在Ruby on Rails中继承自同一基类的多个子类的属性排序? - How can I order by attributes of multiple subclasses that inherit from the same base class in Ruby on Rails? Rails:Ruby类名称必须基于文件名吗? - Rails: ruby class name must base on file name? 如何将其移动到基类,它是一个Ruby枚举 - How to move this to a base class, its a Ruby enumeration 如何更改Rails基础Docker映像的Ruby和Rails版本? - How to change Ruby and Rails version for the Rails base Docker image?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM