megas
megas

Reputation: 21791

Exception policy for Rails API applications

I want to know the general policy how to manage exceptions in Rails API application.

I suppose that the customer should receive only those exceptions that are related to his customer's logic. So in the controller I'm catching these kind of exceptions and sending message of it.

MainApplicationException is a top of hierarchy exception class for all exceptions in my application.

class MyController < ApplicationController

  def some_action

    ... # processing of the request

    rescue MainApplicationException => error
      render: { :message => error.message }
    end
  end
end

But for sure there're big chances that exception will be raised while processing the incoming requests.

How should I register this exceptions and where in the application I should rescue these exceptions? Should I put these message to log? Is there some tutorial for this kind of problem?

Upvotes: 2

Views: 618

Answers (1)

Novae
Novae

Reputation: 1171

Exception handling is hard! In general, and especially when building out an API it's important to have a good grasp of the HTTP status codes. An trivial example of one is a 404. Say for example you're doing Company.find(params[:id] it will throw an ActiveRecord::RecordNotFound and this can be caught all the way up in the application controller: rescue_from ActiveRecord::RecordNotFound, :with => :not_found

The same goes for example for data you have to process, if the format(e.g. you're receiving 'application/xml' instead of 'application/json.') is not as you would accept you can throw an
406.

The hardest part is obviously handling the user data, an important question that arises here is how much do you want to inform the user? Too much information might expose your system for potential hacks.

Personally I find the controller is a good place to handle exceptions IF they don't affect any other parts of the code. Otherwise a nice way to go might be the Builder pattern which allows you to compose a response without actually handling errors in the controller.

There are loads of books on exception handling but an simple introduction on handling API errors and a collection of resources might be this blog post

Hope this helps.

Upvotes: 2

Related Questions