【问题标题】:How to get the component name from the httpInterceptor error handler service in angular?如何以角度从 httpInterceptor 错误处理程序服务获取组件名称?
【发布时间】:2019-06-27 05:06:19
【问题描述】:

我需要在 angular ts 文件中获取发生错误的确切组件名称、函数名称和行号,但我无法从 httpInterceptor 获取它们。请帮助我从 httpInterceptor 获取上述内容。

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

我已经尝试了上述方法,它给出了当前工作组件的组件名称,但我必须从 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));
            })
        )
    }

}```

【问题讨论】:

  • httperror中的错误处理有什么具体原因,什么时候可以在调用组件或服务中处理?
  • @KiraAG 在整个应用程序中处理 HTTP 错误的最佳方法是实现一个常见的 HTTPErrorInterceptor,因为它会拦截每个调用,并且可以轻松处理错误,而无需在每个服务中处理它.
  • @KiraAG ,我想使用 HTTP 拦截器全局处理任何错误。我还需要知道应用程序中哪个组件引发了错误。
  • @M.Sanjay 您不知道哪个组件在您的拦截器中引发了该错误。因为你正在做一个XMLHttpRequest 并且你有上游堆栈的可追溯性
  • @Shifenis 如果有其他方法,请给我建议。

标签: angular angular-http-interceptors


【解决方案1】:

console.trace();

上面的代码有助于完整跟踪错误是如何发生的,以及适当的行号、函数名称和组件名称。因此,我们可以在调试的情况下使用 console.trace(),这对于获取错误发生的位置更有用。

【讨论】:

  • 我想检查组件名称的条件,该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2021-10-19
相关资源
最近更新 更多