Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: validation error codes in JSON

So, I am writing Rails web application which has JSON API for mobile apps. For example, it sends POST JSON request to example.com/api/orders to create order.

{id: 1, order: { product_name: "Pizza", price: 10000}}

In case of validation errors I can response with HTTP 422 error code and order.errors.full_messages in json. But it seems better for me to have specific error code in JSON response. Unfortunately, it seems like Rails does not provide ability to set error code for validation error. How to solve this problem?

like image 414
Andrey Inishev Avatar asked Dec 06 '13 11:12

Andrey Inishev


1 Answers

You can pass a custom status code by using the status option when rendering the response.

def create
  @order = ...

  if @order.save
    render json: @order
  else
    render json: { message: "Validation failed", errors: @order.errors }, status: 400
  end
end

I usually tend to return HTTP 400 on validation errors. The message is a readable status response, the errors are also attached.

This is a respons example

{
    message: "Validation failed",
    errors: [
        ...
    ]
}

You can also embed additional attributes.

like image 93
Simone Carletti Avatar answered Oct 23 '22 12:10

Simone Carletti