Search code examples
angularangular-http-interceptors

How to get the component name from the httpInterceptor error handler service in angular?


I need to get the exact component name, function name and line number where the error has occurred in angular ts file but I cant get them from the httpInterceptor. Please kindly help me to get the above from the httpInterceptor.

console.log(this.route.routeConfig.component.name);

I have tried the above and it gives the component name of the current working component but I have to get the component name from the httpInterceptor.

import { Injectable, ErrorHandler, Input } from '@angular/core';
import { catchError, retry} from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';

@Injectable ({ providedIn: 'root' })
export class errorHandler implements HttpInterceptor{
    constructor(){
    }

    intercept(request : HttpRequest<any>, handler : HttpHandler) : Observable<HttpEvent<any>>{
        return handler.handle(request)
        .pipe(
            retry(1),
            catchError((error : any) => {
                console.log('---->'+request.headers.get('content-disposition'));
                let errorMessage = '';
                if(error.error instanceof ErrorEvent)
                    errorMessage = `Error : `+error.error.message;
                else
                    errorMessage = `Error Code : `+error.status +`\nMessage : `+error.message;

                return throwError(JSON.stringify(errorMessage));
            })
        )
    }

}```

Solution

  • console.trace();

    The above code helps to get the complete trace of how the error occurred along with appropriate line number, function name and the component name. So, we can use console.trace() in case of debugging, which is more useful in case to get where the error occurred.