Rails:JSON中的验证错误代码 [英] Rails: validation error codes in JSON

查看:109
本文介绍了Rails:JSON中的验证错误代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在编写具有用于移动应用程序的JSON API的Rails Web应用程序.例如,它将JSON POST请求发送到example.com/api/orders以创建订单.

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}}

如果发生验证错误,我可以使用HTTP 422错误代码和json中的order.errors.full_messages进行响应.但是对我来说,在JSON响应中包含特定的错误代码似乎更好.不幸的是,似乎Rails没有提供为验证错误设置错误代码的功能.如何解决这个问题?

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?

推荐答案

呈现响应时,可以使用status选项传递自定义状态代码.

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

我通常会因验证错误而返回HTTP 400.该消息是可读的状态响应,错误也会附加.

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

这是一个回应示例

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

您还可以嵌入其他属性.

You can also embed additional attributes.

这篇关于Rails:JSON中的验证错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆