jsonapi-rb / jsonapi-rails

Rails gem for fast jsonapi-compliant APIs.
http://jsonapi-rb.org
MIT License
319 stars 63 forks source link

Render error when unable to deserialize resource #96

Open JoeWoodward opened 5 years ago

JoeWoodward commented 5 years ago

Adds config option to set what happens when unable to deserialize payload

  # config.jsonapi_payload_malformed = -> {
  #   render jsonapi_errors: {
  #     title: 'Non-compliant Request Body',
  #     detail: 'The request was not formatted in compliance with the application/vnd.api+json spec',
  #     links: {
  #       about: 'http://jsonapi.org/format/'
  #     }
  #   }, status: :bad_request
  # }

Able to override on controller by controller basis Tested!

beauby commented 5 years ago

Thanks for all your work @JoeWoodward, and sorry not to have replied earlier. I would lean towards mimicking what happens when a broken JSON payload is set with content-type application/json, which is, IIRC, to raise an exception, which can be rescued by the controller. What do you think?

JoeWoodward commented 5 years ago

No worries @beauby, open source is hard work. It's like a second job :D. I'm happy you made these gems in the first place, they're really good.

I was trying to avoid using exceptions for flow control as I don't believe it really adds any benefit, I believe most libraries use it as they can't be sure where they are in the flow so it's easier to just blow an exception and let the developer handle it. In our case we do have access and control of the controller so IMO makes more sense to actually render an error

I think this solution has another benefit too, if we raise an exceptions which is not handled the server will return a 500 error (which I just realized is currently not handled so probably also needs a PR) which is not very helpful when you're trying to use a json api. I actually implemented this for that exact reason, the mobile devs were complaining that they weren't sure if it was because of their code or mine when they were getting 500 errors when my controller actions where trying to access the nil deserialized object.

You made me realize something, if the config is nil then I am returning in this PR. I think that should actually raise an error

https://jsonapi.org/format/#errors-processing from this link, the spec does permit us responding with 4XX errors