Project

railerr

0.0
The project is in a healthy, maintained state
A declarative, fire and forget way to handle errors in a REST API
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 11.1
~> 3.11
~> 0.21
~> 2.0
 Project Readme

RailErr

A declarative, fire and forget way to handle errors in a rails REST API, and associate each error to an HTTP status code.

Basic Usage

Add a rescue_from block to your controller to rescue APIException exceptions and render the appropriate response:

class ApplicationController < ActionController::API
  rescue_from Railerr::APIException do |e|
    render json: { error: e.message }.to_json, status: e.status_code
  end
end

Now just raise your error inside your application and it will automatically be cast to the appropriate HTTP status.

class SomethingReader < ApplicationService
  def call
    # Do Something
    raise Railerr::BadRequstError if params.invalid?
    raise Railerr::NotFoundError, 'Something not found' if something_not_found
  end
end

The above example will result in the following for the BadRequestError:

  # HTTP/1.1 400 Bad Request
  {
    "error": "Bad request"
  }

And raising with a custom message, as for the NotFoundError:

  # HTTP/1.1 404 Not Found
  {
    "error": "Something not found"
  }

Custom Errors

Custom API Exception classes can be created through inheritance. You can override HTTP status code and default error message by defining the STATUS_CODE and DEFAULT_MESSAGE constants on your custom Exception

class MyCustomError < APIException
  DEFAULT_MESSAGE = 'Custom error message' # Overrides the message inherited from APIException
  STATUS_CODE = Status::HTTP_400_BAD_REQUEST # Overrides the status code inherited from APIException
end