1

我正在使用 aurelia auth 登录。但我无法从服务器收到错误消息。在 catch 方法中,err.response 是未定义的。Err 是具有可读流类型的主体的对象。下面是我的代码:

this.auth.login(bodyContent)
  .then(response=>{
  })
  .catch(err=>{
    console.log(err);
    console.log(err.response);
  });

在 chrome 开发人员工具中,我可以看到响应消息。这是错误的打印:

在此处输入图像描述

4

2 回答 2

2

我在这里找到了解决方案(https://gist.github.com/bryanrsmith/14caed2015b9c54e70c3),它如下:

.catch(error => error.json().then(serverError =>
  console.log(serverError) 
}));

可以在 Aurelia 文档中找到解释:

Fetch API 没有在请求正文中发送 JSON 的便捷方式。对象必须手动序列化为 JSON,并Content-Type适当设置标头。aurelia-fetch-client 包含一个json为此调用的助手。

于 2016-09-07T09:49:45.117 回答
1

我最近也遇到了同样的问题。

我最终创建了一个名为 FetchError 的类来封装这些类型的错误。然后,每当在获取期间发生错误时,我都会抛出 FetchError。

登录.ts:

import { FetchError } from '../../errors';

  login() {
    var credentials = { grant_type: "password", username: this.username, password: this.password };
    return this.auth.login(credentials, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
      .then((response) => {
        return this.auth;
      }).catch(err => {
        this.errorMessage = "Login failed";
        throw new FetchError("Unable to log in", err);
      });
  };

FetchError 类使用“http-status-codes”节点模块来查找文本描述。

错误.ts:

import * as HttpStatus from 'http-status-codes';

export class BaseError extends Error {
  constructor(message) {
    super(message);
    this.message = message;
  }
}

export class FetchError extends BaseError {
  statusCode: number;
  statusText: string;
  description: string;

  constructor(message: string, err: any) {
    super(message);

    if (err instanceof Response) {
      var resp = <Response>err;
      this.statusCode = resp.status;

      if (resp.status == 12029)
        this.statusText = "A connection to server could not be established";
      else
        this.statusText = HttpStatus.getStatusText(resp.status);

      resp.json()
        .then(body => {
          this.description = body.Message;
          console.log(`Error: ${this.message}, Status: ${this.statusText}, Code: ${this.statusCode}, Description: ${this.description}`);
        })
    }
    else if (err instanceof Error) {
      var error = <Error>error;
      this.description = err.message;
      console.log(`Error: ${this.message}, Description: ${this.description}`);
    }
    else {
      this.description = "???";
      console.log(`Unknown error: ${this.message}`);
    }
  }
}

我确信有更好的方法来做到这一点。我还在纠结这个。

于 2016-09-08T04:24:26.000 回答