tiagopog / jsonapi-utils

Build JSON API-compliant APIs on Rails with no (or less) learning curve.
MIT License
216 stars 80 forks source link

Add helper/util method for rendering an object's errors? #6

Closed mecampbellsoup closed 8 years ago

mecampbellsoup commented 8 years ago

It's very common to see a pattern like this in a Rails controller (I'm using jsonapi-utils methods in the code):

if model.save
  jsonapi_render json: model
else
  jsonapi_render json: model.errors # doesn't work
end

Seems like this gem should expose a helper for this type of failed POST request, e.g. jsonapi_render_unprocessable model.errors which would serve 422 response with a response body listing the reasons why the model couldn't be written to the DB.

Not sure what JSONAPI spec says about this, however...

mecampbellsoup commented 8 years ago

This would be the relevant part of the JSON API spec to follow when implementing this: http://jsonapi.org/format/#error-objects

@tiagopog what do you think?

tiagopog commented 8 years ago

Sorry for the long delay, @mecampbellsoup. These last days were really tough at work.

Well, initially we did not get focused on error templates, so now it's open for developers to write their own exception classes. Like this one we have in a production project:

lib/api/v2/exceptions.rb

module API
  module V2
    module Exceptions
      include do
        helper_method :consumer_auth_error, :active_record_error, :unauthorized_error #...
      end

      #...

      # 5
      def active_record_error(object)
        raise ActiveRecordError.new(object)
      end

      ##########################################
      # 5. Any ActiveRecord errors
      ##########################################
      class ActiveRecordError < ::JSONAPI::Exceptions::Error
         attr_accessor :object, :status

        def initialize(object)
          @object = object
          @status = :unprocessable_entity
        end

        def errors
          [JSONAPI::Error.new(code: JSONAPI::ACTIVE_RECORD_ERROR,
                              status: @status,
                              title: "Impossible to change this #{@object.class.name}",
                              detail: @object.errors)]
        end
      end

      #...
    end
  end
end

The actual render goes in the base controle:

_app/controllers/api/v2/basecontroller.rb

module API
  module V2
    class BaseController < JSONAPI::ResourceController
      include JSONAPI::Utils
      include Exceptions

      rescue_from Exceptions::ActiveRecordError, with: :jsonapi_render_errors

      def jsonapi_render_errors(exception)
        render json: { errors: exception.errors }, status: exception.status
      end
    end
  end
end

Then when there is a validation error, for instance:

_app/controllers/api/v2/userscontroller.rb

# POST /api/v2/businesses
def create
  @business = Business.new(custom_business_params)
  @business.save!
   jsonapi_render json: @business
rescue ActiveRecord::ActiveRecordError
  active_record_error @business
end

That will produce the following error response:

HTTP 422 Unprocessable Entity

{
  "errors": [
    {
      "title": "Impossible to change this Business",
      "detail": {
        "name": [
          "can't be blank"
        ]
      },
      "id": null,
      "href": null,
      "code": 125,
      "source": null,
      "links": null,
      "status": "422",
      "meta": null
    }
  ]
}

By the way, I guess it's an awesome idea to deal with these kinda common errors in some handy helper methods. I'll be really excited to work on this functionality in the coming days. For now could you try to implement something like the example above on your project?

mecampbellsoup commented 8 years ago

@tylermachen some helpful stuff in here regarding our current work on serializing errors in accordance with JSON API spec 😄

@tiagopog Yea, we have been working towards a solution for standardizing this, so we may even be able to just open a PR with said helper in it - give us a little time, but also happy to look at anything you produce in the coming days too 😉

mecampbellsoup commented 8 years ago

@tiagopog I guess such a json_render_errors method would generate "standard" error objects in the style of JSON API's examples: http://jsonapi.org/examples/#error-objects-basics

I think I'll revisit this once we've seen how we end up handling API errors. The code you pasted above is looking similar to how we're going to approach it, i.e. catch an exception, instantiate an Error object that has an #errors method that returns a list of descriptive hashes for each error.

tiagopog commented 8 years ago

Hey there, @mecampbellsoup. I started working on it on this weekend. I really appreciated your feedback and I'm sure it will be a great feature. For now I had to stop this work in order to review our test suite first – I'm turning it into something simpler –, but I may go back to that feature asap.