Haseeb Ahmad
Haseeb Ahmad

Reputation: 8730

How to define custom error codes for api in rails

I want to define custom error codes in my api response like

{ status: 401,message: "Authentication issue",code: 1000}

I want to define this 1000 code in my app with some documentation of explanation. How can I do that?

Upvotes: 2

Views: 2413

Answers (1)

Moamen Naanou
Moamen Naanou

Reputation: 1713

First you need to define your custom exception:

class API::Unauthorized < StandardError
  attr_reader :code

  def initialize(code)
    super
    @code = code
  end
end

Then in your APIController, use rescue_from, so add the following:

rescue_from StandardError, :with => :exception_handler

def exception_handler(exception)
  if exception.is_a? API::Unauthorized
    render json: { status: 401, message: "Authentication issue", code: exception.code }, status: unauthorized
  end
end

Now you can throw different exception codes based on your implementation by:

raise API::Unauthorized.new(1000)

Upvotes: 2

Related Questions