0
//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返回errorHttpErrorResponse(这是预期的类型。但是,来自解析器的错误返回error为 type Error

当错误源自解析器时,自定义错误类型会丢失,并且仅返回泛型Error类型。

4

2 回答 2

3

基于这里的问题。当解析器抛出错误时,它会收到被拒绝的错误。所以你失去了原来的错误。下面的代码解决了这个问题。

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');
        }
    }
}
于 2018-09-25T18:22:47.703 回答
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)
        }
    }
}
于 2018-09-25T14:05:24.667 回答