使用(现在默认)Ember Data JSON-API适配器处理错误 [英] Handling errors with the (now default) Ember Data JSON-API adapter

查看:125
本文介绍了使用(现在默认)Ember Data JSON-API适配器处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ember 1.13.7和Ember Data 1.13.8,默认情况下使用JSON-API标准格式化发送到API并从API接收的有效载荷。



我想使用Ember Data的内置错误处理,以便向用户显示红色的错误表单字段。我根据JSON-API标准格式化了我的API错误回复,例如

  {errors:[
{
title:include.1.attributes.street名称字段是必需的,
code:API_ERR,
status:400,
}
]}

当我尝试保存我的模型错误回调正在执行。如果我在Ember Inspector内部看到,我可以看到模型的isError值设置为true,但是我看不到Ember Data如何知道模型中哪个字段是错误状态的那个?我可以从正式的JSON-API页面( http://jsonapi.org/format/#errors )看到,您可以包括错误响应中的源对象:


source:包含引用错误源的对象,
可选包括以下任何成员:


指针:请求文档中关联实体的JSON指针[RFC6901]
[例如/ data为主数据对象,或/ data / attributes / title
为特定属性]。



参数:指示哪个查询
参数导致错误的字符串。





这是我应该做什么来告诉Ember Data哪些字段应该被标记为处于错误状态?



谢谢。

解决方案

请注意以下答案基于以下版本:

  DEBUG:--- ---------------------------- 
ember.debug.js:5442DEBUG:Ember:1.13.8
ember .debug.js:5442DEBUG:Ember数据:1.13.9
ember.debug.js:5442DEBUG:jQuery:1.11.3
DEBUG:-------------- -----------------

错误处理文档不幸的是,在处理不同适配器(Active,REST,JSON)的错误的方式的时候,都有所不同



在您的情况下,您想要处理表单的验证错误,这可能意味着验证错误。 JSON API指定的错误格式可以在这里找到: http://jsonapi.org/format/#error-objects



您会注意到API仅指定错误返回的顶级数组,由错误和所有其他错误属性是可选的。所以似乎所有的JSON API都需要如下:

  {
errors:[
{ }
]
}

当然这不会真的做任何事情对于使用Ember Data和JSONAPIAdapter开箱即用的错误,您将需要至少包含 detail 属性和源/指针属性。 detail 属性被设置为错误消息,并且源/指针属性使Ember Data能够计算出哪个属性在模型中引起问题。因此,Ember Data要求的一个有效的JSON API错误对象(如果您使用的是现在为默认值的JSONAPI),就是这样的:

 code> {
errors:[
{
detail:属性is-admin是必需的,
source:{
pointer:data / attributes / is-admin
}
}
]
}
detail 不是复数(对我来说是一个常见的错误),而$ $ c $的值c> source / pointer 不应该包含前导斜杠,并且属性名称应该被dasherized。



最后,您必须使用HTTP代码 422 返回验证错误,这意味着无法处理的实体。如果您不返回 422 代码,那么默认情况下,Ember Data将返回一个 AdapterError ,并且不会设置错误消息在模型的错误哈希。这让我有一段时间,因为我使用HTTP代码 400 (错误请求)将验证错误返回给客户端。



ember数据区分两种错误的方式是验证错误返回一个 InvalidError 对象( http://emberjs.com/api/data/classes/DS.InvalidError.html )。这将导致模型上的错误哈希设置,但不会将 isError 标志设置为true(不确定为什么会出现这种情况,但这里记录在案: http://emberjs.com/api/data /classes/DS.Model.html#property_isError )。默认情况下,除 422 之外的HTTP错误代码将导致返回的 AdapterError isError 标志设置为 true 。在这两种情况下,承诺的拒绝处理程序将被调用。

  model.save()。then(function(){
// yay!它工作
},function(){
//由于某些原因可能出现错误请求(400)
//可能有验证错误(422)
}

默认情况下,返回的HTTP代码为 422 ,并且您具有正确的JSON API错误格式,那么您可以通过访问模型的错误哈希来访问错误消息,其中哈希键是属性名称。哈希键以骆驼盒格式的属性名称键入。



例如,在我们上面的json-api错误示例中,如果 is-admin 将访问该错误:

  model.get('errors.isAdmin'); 

这将返回一个包含错误对象的数组,格式如下:

  [
{
att 贡献:isAdmin,
message:属性is-admin是必需的
}
]

本质上细节被映射到消息 source / pointer 映射到属性。返回一个数组,以防在单个属性上有多个验证错误(JSON API允许您返回多个验证错误,而不是仅返回第一个验证失败)。您可以直接在这样的模板中使用错误值:

  {{#each model.errors.isAdmin as | error | }} 
< div class =error>
{{error.message}}
< / div>
{{/ each}}

如果没有错误,显示任何东西,所以它很好地做表单验证消息。



如果您的API不使用HTTP 422 代码进行验证错误(例如,如果它使用 400 ),那么您可以通过覆盖自定义适配器中的 handleResponse 方法来更改JSONAPIAdapter的默认行为。以下是一个示例,为 400 的任何HTTP响应状态代码返回一个新的 InvalidError 对象。

 从ember-data导入DS; 
从ember导入Ember;

导出默认DS.JSONAPIAdapter.extend({
handleResponse:function(status,headers,payload){
if(status === 400&& payload.errors ){
return new DS.InvalidError(payload.errors);
}
return this._super(... arguments);
}
});

在上面的例子中,我检查HTTP状态是否为 400 ,并确保存在错误属性。如果是这样,那么我创建一个新的 DS.InvalidError 并返回。这将导致与预期 422 HTTP状态代码的默认行为相同的行为(即,您的JSON API错误将被处理,并将消息放入错误哈希中模型)。



希望有帮助!


I am using Ember 1.13.7 and Ember Data 1.13.8, which by default use the JSON-API standard to format the payloads sent to and received from the API.

I would like to use Ember Data's built-in error handling in order to display red "error" form fields to the user. I have formatted my API error responses as per the JSON-API standard, e.g.

{"errors":[
    {
        "title":"The included.1.attributes.street name field is required.", 
        "code":"API_ERR", 
        "status":"400", 
    }
]}

and when I attempt to save my model the error callback is being correctly executed. If I look within the Ember Inspector I can see that the model's "isError" value is set to true but I can't see how Ember Data is supposed to know which field within the model is the one in an error state? I see from the official JSON-API pages (http://jsonapi.org/format/#errors) that you can include a "source" object within the error response:

source: an object containing references to the source of the error, optionally including any of the following members:

pointer: a JSON Pointer [RFC6901] to the associated entity in the request document [e.g. "/data" for a primary data object, or "/data/attributes/title" for a specific attribute].

parameter: a string indicating which query parameter caused the error.

but is this what I should be doing in order to tell Ember Data which fields it should mark as being in an error state?

If anyone can help shed some light on this I'd be grateful.

Thanks.

解决方案

Note the answer below is based on the following versions:

DEBUG: -------------------------------
ember.debug.js:5442DEBUG: Ember                     : 1.13.8
ember.debug.js:5442DEBUG: Ember Data                : 1.13.9
ember.debug.js:5442DEBUG: jQuery                    : 1.11.3
DEBUG: -------------------------------

The error handling documentation is unfortunately scattered around at the moment as the way you handle errors for the different adapters (Active, REST, JSON) are all a bit different.

In your case you want to handle validation errors for your form which probably means validation errors. The format for errors as specified by the JSON API can be found here: http://jsonapi.org/format/#error-objects

You'll notice that the API only specifies that errors are returned in a top level array keyed by errors and all other error attributes are optional. So seemingly all that JSON API requires is the following:

{
    "errors": [
     {}
    ]
}  

Of course that won't really do anything so for errors to work out of the box with Ember Data and the JSONAPIAdapter you will need to include at a minimum the detail attribute and the source/pointer attribute. The detail attribute is what gets set as the error message and the source/pointer attribute lets Ember Data figure out which attribute in the model is causing the problem. So a valid JSON API error object as required by Ember Data (if you're using the JSONAPI which is now the default) is something like this:

{
    "errors": [
     {
        "detail": "The attribute `is-admin` is required",
        "source": {
             "pointer": "data/attributes/is-admin"
         }
     }
    ]
}  

Note that detail is not plural (a common mistake for me) and that the value for source/pointer should not include a leading forward slash and the attribute name should be dasherized.

Finally, you must return your validation error using the HTTP Code 422 which means "Unprocessable Entity". If you do not return a 422 code then by default Ember Data will return an AdapterError and will not set the error messages on the model's errors hash. This bit me for a while because I was using the HTTP Code 400 (Bad Request) to return validation errors to the client.

The way ember data differentiates the two types of errors is that a validation error returns an InvalidError object (http://emberjs.com/api/data/classes/DS.InvalidError.html). This will cause the errors hash on the model to be set but will not set the isError flag to true (not sure why this is the case but it is documented here: http://emberjs.com/api/data/classes/DS.Model.html#property_isError). By default an HTTP error code other than 422 will result in an AdapterError being returned and the isError flag set to true. In both cases, the promise's reject handler will be called.

model.save().then(function(){
    // yay! it worked
}, function(){
    // it failed for some reason possibly a Bad Request (400)
    // possibly a validation error (422)
}

By default if the HTTP code returned is a 422 and you have the correct JSON API error format then you can access the error messages by accessing the model's errors hash where the hash keys are your attribute names. The hash is keyed on the attribute name in the camelcase format.

For example, in our above json-api error example, if there is an error on is-admin your would access that error like this:

model.get('errors.isAdmin');

This will return an array containing error objects where the format is like this:

[
   {
      "attribute": "isAdmin",
      "message": "The attribute `is-admin` is required"
    }
]

Essentially detail is mapped to message and source/pointer is mapped to attribute. An array is returned in case you have multiple validation errors on a single attribute (JSON API allows you to return multiple validation errors rather than returning just the first validation to fail). You can use the error values directly in a template like this:

{{#each model.errors.isAdmin as |error|}}
    <div class="error">
      {{error.message}}
    </div>
{{/each}}

If there are no errors then the above won't display anything so it works nicely for doing form validation messages.

If you API does not use the HTTP 422 code for validation errors (e.g., if it uses 400) then you can change the default behavior of the JSONAPIAdapter by overriding the handleResponse method in your custom adapter. Here is an example that returns a new InvalidError object for any HTTP response status code that is 400.

import DS from "ember-data";
import Ember from "ember";

export default DS.JSONAPIAdapter.extend({
  handleResponse: function(status, headers, payload){
    if(status === 400 && payload.errors){
      return new DS.InvalidError(payload.errors);
    }
    return this._super(...arguments);
  }
});

In the above example I'm checking to see if the HTTP status is 400 and making sure an errors property exists. If it does, then I create a new DS.InvalidError and return that. This will result in the same behavior as the default behavior that expects a 422 HTTP status code (i.e., your JSON API error will be processed and the message put into the errors hash on the model).

Hope that helps!

这篇关于使用(现在默认)Ember Data JSON-API适配器处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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