Skip to content

Instantly share code, notes, and snippets.

@teomanofficial
Last active August 31, 2022 06:41
Show Gist options
  • Save teomanofficial/22208a1ff06e949c6eed97d4bb08f4b5 to your computer and use it in GitHub Desktop.
Save teomanofficial/22208a1ff06e949c6eed97d4bb08f4b5 to your computer and use it in GitHub Desktop.
Setup Global Error Handler Using Interceptor
// 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