//api.service.ts
public Get(slug: string): Observable<T> {
return this.http.get(`${environment.apiBaseURL}/${this.endPoint}/${slug}`).pipe(
map(data => this.serializer.fromJson(data) as T)
);
}
//global-error-handler.ts
import { Injectable, ErrorHandler } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: any) {
if (error instanceof HttpErrorResponse) {
console.log('type is HttpErrorResponse');
}
else
{
console.log('type is Error');
}
}
}
//app.module.ts
{
provide: ErrorHandler,
useClass: GlobalErrorHandler,
}
来自具有subscribe
的组件的错误返回error
作为HttpErrorResponse
(这是预期的类型。但是,来自解析器的错误返回error
的类型Error
当错误源自解析器时,自定义错误类型将丢失,并且仅返回通用Error
类型。
答案 0 :(得分:1)
基于issue here。从解析器抛出错误时,它得到拒绝的错误。因此您失去了原始错误。下面的代码解决了该问题。
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: any) {
error = error.rejection ? error.rejection : error; //this fixes the problem
if (error instanceof HttpErrorResponse) {
console.log('type is HttpErrorResponse');
}
else {
console.log('type is Error');
}
}
}
答案 1 :(得分:0)
如果仅调用Get而没有catchError怎么办
public Get(slug: string): Observable<T> {
return this.http.get(`${environment.apiBaseURL}/${this.endPoint}/${slug}`)
.pipe(map(data => this.serializer.fromJson(data) as T))
}
并在全局ErrorHandler中处理所有404/500错误
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: any): void {
if (error.status === 404) {
console.log('404 Error happened')
// TODO handle error here (redirect)
}
}
}