我最近也遇到了同样的问题。
我最终创建了一个名为 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}`);
}
}
}
我确信有更好的方法来做到这一点。我还在纠结这个。