How to Raise and Rescue Errors in Rails
30 Aug 2016Raising and rescuing errors in Rails is relatively easy. All you need to do is make a custom error class, raise it (usually in a model) and rescue it (usually in a controller).
Start by making a custom error class that inherits from StandardError. This will give you a more descriptive error instead of raising the generic StandardError, so you can better deduce where the error came from. I will use a hypothetical example of an error that is raised when a User is being created.
class UserCreateError < StandardError
end
Each custom error class should have it’s own file which you can put in an app/errors directory.
Here I will raise the error in a User model method.
class User < ActiveRecord::Base
def self.example_method
raise UserCreateError
end
end
When the create action is called on the controller, it will call User.example_method, which will raise the error. The error then goes back up to the controller where it is rescued.
class UsersController < ApplicationController
def create
User.example_method
rescue UserCreateError
render json: "Invalid User Information", status: :bad_request
end
end
Note the indentation of the rescue is on the same column as the def.
Whatever you put underneath the rescue will be run if there is an error.
Here I render a custom json error message and specify an optional status code.
And that’s pretty much all there is too it.