Angular ErrorHandler passed incorrect data

193 views Asked by At
//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.

2

There are 2 answers

0
Joe On BEST ANSWER

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

What if you just call Get without the 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))
}

and inside your global ErrorHandler you handle all 404/500 Errors

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

    handleError(error: any): void {
        if (error.status === 404) {
             console.log('404 Error happened')
             // TODO handle error here (redirect)
        }
    }
}