0

I have an Angular 9 project that works with a .NET Core WEB API. The site features user authentication that is role based. The API returns two types of errors: 401 and 403 depending on the authorization rules for a controller method.

My goal is to display a message in my layout component when the API returns any of these errors, for example:

  • 401: 'Session has expired, please log in.'
  • 403: 'You do not have access to this feature.'

Is there any way to catch these errors in Angular and know which one was thrown?

1 Answer 1

1

You can use interceptors to catch every http requests. In your case you need to catch response. To do it;

At the module which you provided 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);
      }),
    );
  }
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, very descriptive, I'll upvote and of it works for me I'll mark it as an answer
I'm having a problem with the name 'catchError'. The error message is "Cannot find name 'catchError'. Did you mean 'RTCError'?". Am I missing any imports or something?
You can import it from "rxjs/operators" @JohannesKarsten

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.