jsonapi-rails icon indicating copy to clipboard operation
jsonapi-rails copied to clipboard

Consider having the renderer decide on success/error with status code.

Open beauby opened this issue 8 years ago • 1 comments
trafficstars

Instead of having render jsonapi: foo and render jsonapi_errors: errors, simply have render jsonapi: foo and render jsonapi: errors, status: 400.

beauby avatar Sep 19 '17 15:09 beauby

Thanks for this comment. Solved it as follows:

#controllers/api/v1/api_controller.rb

class ApiController < ApplicationController
  include ExceptionHandler
end

#controllers/api/v1/concerns/ExceptionHandler.rb

module ExceptionHandler
  # provides the more graceful `included` method
  extend ActiveSupport::Concern
  included do
    rescue_from Exception do |exception|
      case exception
      when ActiveRecord::RecordNotFound
        render jsonapi_errors: {message: exception.message}, status: :not_found
      when ActiveRecord::RecordInvalid
        render jsonapi_errors: {message: exception.message}, status: :unprocessable_entity
      # else
        # figure out how to render_500
      end
    end
  end
end

nuheluxulu avatar Jun 07 '19 22:06 nuheluxulu