简体   繁体   English

Rails:JSON中的验证错误代码

[英]Rails: validation error codes in JSON

So, I am writing Rails web application which has JSON API for mobile apps. 所以,我正在编写Rails web应用程序,该应用程序具有用于移动应用程序的JSON API。 For example, it sends POST JSON request to example.com/api/orders to create order. 例如,它将POST JSON请求发送到example.com/api/orders以创建订单。

{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. 在验证错误的情况下,我可以使用HTTP 422错误代码和json中的order.errors.full_messages进行响应。 But it seems better for me to have specific error code in JSON response. 但我觉得在JSON响应中有特定的错误代码似乎更好。 Unfortunately, it seems like Rails does not provide ability to set error code for validation error. 不幸的是,似乎Rails没有提供为验证错误设置错误代码的能力。 How to solve this problem? 如何解决这个问题呢?

You can pass a custom status code by using the status option when rendering the response. 您可以在呈现响应时使用status选项传递自定义状态代码。

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. 我通常倾向于在验证错误上返回HTTP 400。 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. 您还可以嵌入其他属性。

I was after something similar, so what I did was extend String eg 我是在追求类似的东西,所以我做的是扩展String例如

class ErrorCodeString < String
  def init(value, error_code)
     @error_code = error_code
     super(value)
  end

  def error_code
      @error_code
  end
end

Then in a custom validation (this won't work on standard validation) I'd do 然后在自定义验证中(这不适用于标准验证)我会这样做

 errors.add(:email, ErrorCodeString.new('cannot be blank', 50)

Now when you return your JSON you can check to see if the error value is an ErrorCodeString and add the error_code value to the output. 现在,当您返回JSON时,您可以检查错误值是否为ErrorCodeString并将error_code值添加到输出中。 As ErrorString inherits String, you shouldn't be breaking anything else along the way. 由于ErrorString继承了String,因此在此过程中不应该破坏其他任何东西。

Rails 5 has error.details that can be used for exactly that. Rails 5有error.details,可以用于它。

In the model 在模型中

errors.add(:price, 1023, message: "Transaction value #{price} is above limit (#{maximum_price}).")

In the controller 在控制器中

format.json { render json: @order.errors.details, status: :unprocessable_entity }

error details can be anything, eg. 错误细节可以是任何东西,例如。 you could also use :above_limit instead of 1023. The API response body will then look like 您也可以使用:above_limit而不是1023. API响应正文将如下所示

pp JSON.parse(response)
{"price"=>[{"error"=>1023}]}

This feature has been backported to Rails 4, see also http://blog.bigbinary.com/2016/05/03/rails-5-adds-a-way-to-get-information-about-types-of-failed-validations.html 此功能已被移植到Rails 4,另请参阅http://blog.bigbinary.com/2016/05/03/rails-5-adds-a-way-to-get-information-about-types-of-failed -validations.html

Also: Is there a way to return error code in addition to error message in rails active record validation? 另外: 除了rails活动记录验证中的错误消息之外,还有办法返回错误代码吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM