【问题标题】:Angular catch errors in a central place or component在中心位置或组件中捕获错误
【发布时间】:2020-06-03 12:38:35
【问题描述】:

我有一个使用 .NET Core WEB API 的 Angular 9 项目。 该站点具有基于角色的用户身份验证。 API 返回两种类型的错误:401 和 403,具体取决于控制器方法的授权规则。

我的目标是在 API 返回任何这些错误时在我的布局组件中显示一条消息,例如:

  • 401: '会话已过期,请登录。'
  • 403: '您无权使用此功能。'

有没有办法在 Angular 中捕获这些错误并知道是哪个错误被抛出?

【问题讨论】:

    标签: authentication .net-core error-handling angular9


    【解决方案1】:

    您可以使用拦截器来捕获每个 http 请求。在您的情况下,您需要捕捉响应。去做;

    在你提供的模块上 HttpClientModule (app/core).module.ts

    import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
    import { HttpErrorInterceptor } from '<path of interceptor>';
    
    @NgModule({
    imports: [HttpClientModule],
    providers: [
         {
          provide: HTTP_INTERCEPTORS,
          useClass: HttpErrorInterceptor,
          multi: true,
        },
      ]
    });
    

    error.interceptor.ts

    export class HttpErrorInterceptor implements HttpInterceptor {
      constructor(
          // your injections if you need
      ) {}
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
          catchError((err: HttpErrorResponse) => {
            switch (err.status) {
              case 401: {
                this.handle401();
              }
              case 403: {
                this.handle403();
              }
            }
            return throwError(err);
          }),
        );
      }
    

    【讨论】:

    • 谢谢你,描述性很强,我会投票赞成,它对我有用,我会把它标记为答案
    • 我遇到了名称“catchError”的问题。错误消息是“找不到名称'catchError'。您的意思是'RTCError'吗?”。我错过了任何进口或其他东西吗?
    • 您可以从“rxjs/operators”@JohannesKarsten 导入它
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多