Search code examples
angularresthttpangular-http-interceptors

Angular interceptor should not intercept bad requests


I am writing a web app in Angular 8, which gets data from a .NET Core backend. It authenticates using JWT tokens, and if the token is not valid, the backend gives a 401 Not Authorized error code. To handle this correct in Angular, I added a http interceptor:

import { Injectable } from '@angular/core';
import {
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpInterceptor,
    HttpErrorResponse,
    HttpResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import {catchError, finalize, first, tap} from 'rxjs/operators';
import {AuthenticationService} from "../_services/authentication.service";

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).observ((err) => {
                if (err.status === 401) {
                    // auto logout if 401 response returned from api
                    this.authenticationService.logout();
                    location.reload(true);
                }

                const error = err.error.message || err.statusText;

                console.log("Hij komt als allerlaatste hier, waar de error");
                console.log(error);
         });
    }
}

For now this works correct. However, I am adding a register page and if the email is already in use, users should get an error. The backend gives then a response with status code 400 Bad Request, but I want to get this error in my own code, where I sent the request, to handle user messages correctly.

I tried to use tap(), but the bad request error is catched as error by the catchError function.

How should I solve this issue correctly?


Solution

  • You can use throwError() from rxJs, so if the response is 400 you just throw an error and catch it in your service, so Just add 1 more if condition for Bad Request with error code 400 like this:

    if (err.status === 400) {
           const error = err.error.message || err.statusText;
           return throwError(error);
    }