处理错误时如何在 ember-data 中设置自定义响应 json

How to set custom response json in ember-data when dealing with errors

我现在在用:

我正在尝试从 Grails API 发送一个带有一些额外数据的错误响应。 它看起来像这样:

respond(
    status: HttpStatus.UNPROCESSABLE_ENTITY, 
    errors: errors
    additionalData: someMap
)

在 Ember 的前端,我试图用以下方法捕获它:

object.save().then(function () {
    // (...)
}).catch((response) => {
    // Here I want to access "response.additionalData"
    // (...)
});

现在,我知道 ember-data 有自己的方法来处理和绑定错误响应 (https://davidtang.io/2016/01/09/handling-errors-with-ember-data.html),但在 ember-data: 2.10.0 中,我能够使用附加数据捕获和处理错误response.additionalData.

在我使用的版本中,response.additionalData 始终是 undefined,我无法以任何方式获取它。 它来自后端,因为我可以在浏览器开发工具中看到它作为响应。

如何在最新的 ember-data 中实现这一点? 我确实尝试编写 adapter 并覆盖 handleResponse 函数,但即使是我自己的 CustomErrorClass 仍然像原生的一样。

如有任何帮助,我们将不胜感激。 提前致谢!

所以,我确实尝试了几个选项 meta JSONAPI 格式的成员,如下所述:

起初,这没有帮助,服务器的回答是:

Error: Assertion Failed: Your transport record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.

然后我将响应状态添加到 HttpServletResponse response 对象,如下所示:

response.status = HttpStatus.UNPROCESSABLE_ENTITY.value()

所以完整的响应部分如下所示:

response.status = HttpStatus.UNPROCESSABLE_ENTITY.value()
render([errors: [[status: HttpStatus.UNPROCESSABLE_ENTITY,
                  title : e.message,
                  detail: message,
                  meta  : [additionalData: additionalData]]
]] as JSON)

另请注意,为了使 JSONAPI 格式有效,errors 内容在双括号中 [[

有了这个,我终于得到了正确答案,里面有 meta 个成员: