在Angular/Typescript中,可以使用HttpErrorResponse类来捕获不成功的http请求的细节。以下是一个示例代码:
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
constructor(private http: HttpClient) {}
makeUnsuccessfulHttpRequest() {
return this.http.get('http://localhost:3000/unsuccessfulRequest').pipe(
catchError((error: HttpErrorResponse) => {
if (error.error instanceof ErrorEvent) {
// 客户端错误
console.error('An error occurred:', error.error.message);
} else {
// 服务端错误
console.error(`Backend returned code ${error.status}, body was: ${error.error}`);
}
// 返回一个 observable 以便后续处理
return throwError('Something bad happened; please try again later.');
})
);
}
在示例代码中,使用http.get()请求了一个不存在的URL,并通过catchError()函数捕获了错误。如果客户端产生错误,错误对象的error属性将会是一个ErrorEvent的实例,因此可以使用error.message访问错误信息。如果服务端产生错误,错误对象包括状态码error.status和错误消息error.error。最后,使用throwError()函数返回一个Observable以便后续处理错误。
上一篇:Angular/Typescript:拦截器让浏览器发出额外的OPTIONSHTTP请求
下一篇:Angular/Universal应用程序 - 在服务器上未执行https请求(this.httpClient.get)。