代码之家  ›  专栏  ›  技术社区  ›  Joe Scotto

promise catch不解析json

  •  0
  • Joe Scotto  · 技术社区  · 6 年前

    Http 为了发布到我的API,当响应的状态为200时,它会正确地解析它并按预期输出我的响应,我使用第一个 .then() .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响应,所以我不确定为什么我的typescript代码不会解析json .catch()

    我的打字稿由两个文件组成 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);
      });
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   damjtoh    6 年前

    由于您的请求失败(400状态码),它不会通过 then 回调,它将转到 catch 一个,因为你在 post 方法它将冒泡到 register 方法catch,因为您没有解析为json,所以它不会是json。

    试试这个:

    public post(path, params): Promise<any> {
      return this.http
        .post(this.apiUrl + path, params)
        .toPromise()
        .then(r => r.json())
        .catch(e => throw new Error(e.json()));
    }
    
        2
  •  1
  •   smkskr    6 年前

    您可以尝试在中检查状态消息 .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);
      });
    }