如何正确捕获控制器操作中的异常?

时间:2022-06-02 20:57:19

There is the following code:

有以下代码:

def index
  @posts = User.find_by(login: params[:user_id]).posts
end

As you can see this code can generate exception if there is no user with some login (nil pointer exception). How can I catch this exception and handle it properly? I know how to catch exceptions in Ruby, but I want to know how to do in a good Rails style. The same problem may occur in different controllers - may be I should create an action wrapper, catch exception and render 500 error?

如您所见,如果没有用户进行某些登录(nil指针异常),则此代码可能会生成异常。如何捕获此异常并正确处理?我知道如何在Ruby中捕获异常,但我想知道如何以良好的Rails风格进行操作。在不同的控制器中可能会出现同样的问题 - 可能是我应该创建一个动作包装器,捕获异常并呈现500错误?

2 个解决方案

#1


8  

The easiest way is to use ApplicationController's rescue_from:

最简单的方法是使用ApplicationController的rescue_from:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :record_not_found

  private

  def record_not_found
    render 'my/custom/template', status: 404
  end
end

#2


1  

def index
  @posts = User.find_by!(login: params[:user_id]).posts
rescue ActiveRecord::RecordNotFound => error
  # handle user not found case
end

You can also use rescue_from http://edgeapi.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html if you want to catch the error globally for the controller.

如果要全局捕获控制器的错误,也可以使用rescue_from http://edgeapi.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html。

#1


8  

The easiest way is to use ApplicationController's rescue_from:

最简单的方法是使用ApplicationController的rescue_from:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :record_not_found

  private

  def record_not_found
    render 'my/custom/template', status: 404
  end
end

#2


1  

def index
  @posts = User.find_by!(login: params[:user_id]).posts
rescue ActiveRecord::RecordNotFound => error
  # handle user not found case
end

You can also use rescue_from http://edgeapi.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html if you want to catch the error globally for the controller.

如果要全局捕获控制器的错误,也可以使用rescue_from http://edgeapi.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html。