Last active
August 31, 2022 06:41
-
-
Save teomanofficial/22208a1ff06e949c6eed97d4bb08f4b5 to your computer and use it in GitHub Desktop.
Setup Global Error Handler Using Interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Imports | |
@Injectable({ providedIn: 'root' }) | |
export class ErrorHandlerInterceptor implements HttpInterceptor { | |
constructor(private readonly validationErrorService: ValidationErrorsService) { | |
} | |
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
return next.handle(req) | |
.pipe(catchError(event => { | |
if (event instanceof HttpErrorResponse) { | |
if (event.status === HttpErrorStatus.userFriendlyError || event.status === HttpErrorStatus.unauthorizedError || event.status === HttpErrorStatus.notFoundError) { | |
if (req.headers.has(CustomHeaders.skipGlobalErrorhandler)) return throwError(event) | |
this.handleUserFriendError(event); | |
return throwError(event); | |
} | |
if (event.status === HttpErrorStatus.unauthenticatedError) { | |
this.handleAuthenticatedError(event); | |
return throwError(event); | |
} | |
if (event.status === HttpErrorStatus.badRequestError && (event.error as BadRequestResponseModel).type === ErrorType.badRequestType) { | |
this.handleValidationError(event); | |
return throwError(event); | |
} | |
if (event.status === HttpErrorStatus.serverError) { | |
this.handleServerErrors(); | |
return throwError(event); | |
} | |
} | |
return throwError(event); | |
})); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment