angularangular-errorhandler

Angular ErrorHandler passed incorrect data


//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,
}

errors from component which have subscribe returns error as HttpErrorResponse (which is the expected type. however, errors from resolvers return error as type Error.

Custom error types are lost when the error originate from a resolver, and only return the generic Error type.


Solution

  • based on the issue here. it is getting a rejected error when an error is thrown from a resolver. so you're loosing the original error. the code below fixes the problem.

    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');
            }
        }
    }