首页 > 解决方案 > 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 由两个文件组成apiuser用户只需扩展 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);
  });
}

标签: javascriptjsonangularangular-http

解决方案


您可以尝试检查该.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);
  });
}

推荐阅读