当客户端未经身份验证时,我正在使用的 API 返回 200 并带有字符串错误消息。所以如果我打电话:
var restSvc = Restangular.service('message');
var deferred = restSvc.getList()
经过身份验证后,我会返回一个对象数组 - 但如果我在未经过身份验证时调用它,我会返回字符串“调用者无法经过身份验证。”
问题是我无法处理这个错误,因为 Restangular 会抛出一个错误,并且不会解析或使延迟失败,因为它需要一个数组:
Error: Response for getList SHOULD be an array and not an object or something else
如何处理此错误并获取响应,即使它不是数组?
最佳答案
您可以做的一件事是添加响应拦截器以在返回数据之前测试数据。如果它符合特定格式,则将其附加到响应数据中。例如。
restangularConfig.addResponseInterceptor(function(response, operation) {
if (operation === 'getList') {
// Test your data structure here.
}
return response;
});
如果这是您自己设计的 API,我强烈建议更改格式以与每个请求保持一致。例如。
如果请求是好的。
{
"status": 200,
"content": [{},{}...]
}
如果请求不好。
{
"status": 401, //or what ever error
"content": []
}
关于angularjs - 如何处理不是数组的 Restangular .getList() 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24460692/