Skip to content

Instantly share code, notes, and snippets.

@sunilkumarmedium
Created November 22, 2020 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunilkumarmedium/f0aa6b2a6ed52e63f00de9ffbd540f74 to your computer and use it in GitHub Desktop.
Save sunilkumarmedium/f0aa6b2a6ed52e63f00de9ffbd540f74 to your computer and use it in GitHub Desktop.
global-error.service.ts
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { ToastService } from '../toast/toast.service';
@Injectable({
providedIn: 'root'
})
export class GlobalErrorService implements ErrorHandler{
constructor(
private injector: Injector
) { }
handleError(errorResponse: any): void {
if (errorResponse.status === 401) {
this.injector.get(ToastService).danger('Unauthorised: Please login again.');
} else if (errorResponse.status === 400) {
this.injector.get(ToastService).danger(this.formatErrors(errorResponse.error.Errors));
} else {
// All other errors including 500
const error = errorResponse && errorResponse.rejection ? errorResponse.rejection.error : errorResponse;
this.injector.get(ToastService).danger(error.message);
// IMPORTANT: Don't Rethrow the error otherwise it will not emit errors after once
// https://stackoverflow.com/questions/44356040/angular-global-error-handler-working-only-once
// throw errorResponse;
}
}
private formatErrors(errors: any) {
return errors ? errors.map((err: any) => err.PropertyName + ' : ' + err.ErrorMessage).join('<br>') : '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment