【问题标题】:What's the right way to do exception handling in Ruby on Rails? [closed]在 Ruby on Rails 中进行异常处理的正确方法是什么? [关闭]
【发布时间】:2018-07-07 01:02:25
【问题描述】:

假设我有基本控制器:

class ApplicationController < ActionController::Base

另外,我有一些继承的控制器,例如:

class JobController < ApplicationController

我想在JobController 中明确处理一些异常子集,而在ApplicationController 中,我将处理所有剩余的异常。

在 Ruby on Rails 中进行异常处理的正确方法是什么?我知道我们可以使用:rescue_fromaround_action。那么哪个是首选方式呢?

【问题讨论】:

标签: ruby-on-rails ruby exception-handling


【解决方案1】:

我认为将rescue_from 添加到application_controller 是处理异常的好方法。

例如(rails 5.*):

class ApplicationController < ActionController::Base
  rescue_from ::ActiveRecord::RecordNotFound do |exception|
    render plain: exception.message, status: :not_found
  end
end

之后,您将在所有操作中获得:

["Couldn't find * with 'id'=1"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-01
    • 2020-05-23
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    相关资源
    最近更新 更多