Created
November 22, 2020 10:22
-
-
Save sunilkumarmedium/f0aa6b2a6ed52e63f00de9ffbd540f74 to your computer and use it in GitHub Desktop.
global-error.service.ts
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
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