Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch exceptions in controller's actions properly?

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?

like image 435
malcoauri Avatar asked Dec 08 '14 08:12

malcoauri


People also ask

How do you handle exceptions at controller level?

Another way to handle controller level exceptions is by overriding the OnException() method in the controller class. This method handles all your unhandled errors with error code 500. It allows you to log an exception and redirect to the specific view. It does not require to enable the <customErrors> config in web.

How do you handle exceptions in API?

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.

How many ways are there to handle exceptions in MVC?

In ASP.NET MVC we may have three ways to handle exceptions, Try-catch-finally. Exception filter. Application_Error event.


1 Answers

The easiest way is to use ApplicationController's 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
like image 68
Alexander Karmes Avatar answered Oct 18 '22 13:10

Alexander Karmes