javascript - promise catch 不解析 json
问题描述
我正在使用 AngularHttp
发布到我的 API,当响应的状态为 200 时,它会正确解析它并按预期输出我的响应,我在第一个.then()
承诺的情况下处理这个问题,但是当我的 API 出现错误时,我抛出它状态为 400 并尝试通过.catch()
块处理它。
我遇到的问题是,.catch()
我的 api 中不仅有我的原始 json 错误,它只是未定义的。我的 API 的错误响应类似于:
{
"status": 400,
"message": "Bad request",
"errors": [
{
"code": "IN_USE",
"message": "Email is in use",
"field": "email"
}
],
"data": []
}
我已经确保我正在发送application/json
带有 200 和 400 响应的标头,所以我不确定为什么我的打字稿代码不会解析 json.catch()
我的 Typescript 由两个文件组成api
,user
用户只需扩展 api 以使用post()
我创建的方法:
api.ts
/**
* POST to the API
* @param path Where to go
* @param params What to send
*/
public post(path, params): Promise<any> {
return this.http
.post(this.apiUrl + path, params)
.toPromise()
.then(r => r.json());
}
用户.ts
/**
* Registers a user and then logs them in via token
* @param name Users name
* @param email Users email
* @param password Users password
*/
register(name: string, email: string, password: string) {
this.post('/register', {
access_token: this.accessToken,
name: name,
email: email,
password: password
})
.then(r => {
// This logs the json just fine
console.log(r);
})
.catch(r => {
// This is undefined
console.log(r);
});
}
解决方案
您可以尝试检查该.then(r => )
部分中的状态消息,然后根据状态继续执行您的逻辑。
register(name: string, email: string, password: string) {
this.post('/register', {
access_token: this.accessToken,
name: name,
email: email,
password: password
})
.then(r => {
// This logs the json just fine
if(r.status == 200){
console.log(r);
}
if(r.status == 400){
console.log(r);
}
})
.catch(r => {
// This is undefined
console.log(r);
});
}
推荐阅读
- python - Ubuntu 20.04 上的 anaconda 开放终端问题
- python - 在python中使用列表变量实现哈希表
- python - python py2r我如何通过子集搜索
- python - 语音识别(Python):如何解决“RequestError:错误请求”?
- python - 带有 if 语句的 Pandas 新专栏
- swift - Swift:告诉回调在全局队列上运行
- c# - Autofac 和 WCF .Net 4.0 - 在启动时加载长时间运行的数据
- gtk - 在 Gtk.TreeView+Gtk.TreeStore 中,我可以移动缩进的列吗?
- class - Dart 类中的组静态常量
- probability - 贝叶斯网络和条件概率表