Skip to content

Instantly share code, notes, and snippets.

@brachi-wernick
Last active January 14, 2018 11:53
Show Gist options
  • Save brachi-wernick/516ba40cbd70bb7a60f84469030c6424 to your computer and use it in GitHub Desktop.
Save brachi-wernick/516ba40cbd70bb7a60f84469030c6424 to your computer and use it in GitHub Desktop.
handle error
import {ErrorHandler} from "@angular/core";
import {UNAUTHORIZED, BAD_REQUEST, FORBIDDEN} from "http-status-codes";
import {Router} from "@angular/router";
import {ToastsManager, Toast, ToastOptions} from "ng2-toastr";
@Injectable()
export class myAppErrorHandler implements ErrorHandler {
static readonly REFRESH_PAGE_ON_TOAST_CLICK_MESSAGE: string = "An error occurred: Please click this message to refresh";
static readonly DEFAULT_ERROR_TITLE: string = "Something went wrong";
constructor(private router: Router,private toastManager: ToastsManager){};
public handleError(error: any) {
console.error(error);
let httpErrorCode = error.httpErrorCode;
switch (httpErrorCode) {
case UNAUTHORIZED:
this.router.navigateByUrl("/login");
break;
case FORBIDDEN:
this.router.navigateByUrl("/unauthorized");
break;
case BAD_REQUEST:
this.showError(error.message);
break;
default:
this.showError(REFRESH_PAGE_ON_TOAST_CLICK_MESSAGE);
}
}
private showError(message:string){
this.toastManager.error(message, DEFAULT_ERROR_TITLE, { dismiss: 'controlled'}).then((toast:Toast)=>{
let currentToastId:number = toast.id;
this.toastManager.onClickToast().subscribe(clickedToast => {
if (clickedToast.id === currentToastId) {
this.toastManager.dismissToast(toast);
window.location.reload();
}
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment