Angular

Last Updated: 9/5/2023

Global Error Handling for Unexpected Errors

  • Instead of handling unexpected errors in each component, handle it globally
  • In default implementation of this class, angular simply logs error in console
  • In our implementation we want to display an error message to the user and log in server
  • create new common/app-error-handler.ts
  • implement ErrorHandler interface
export class AppErrorHandler implements ErrorHandler {
	handleError(error) {
		alert("An unexpected error occured");
		console.log(error)
	}
}
  • Register as dependency/provider in app.module.ts as a replace for ErrorHandler
  • Tell angular wherever you internally use ErrorHandler instead use AppErrorHandler

app,module.ts

providers: [{ provide: ErrorHandler, useClass: AppErrorHandler }]
  • Remove error handler function in ngOnit and allow the error to propagate our app and eventually hit global error handler

posts.component.ts

ngOnInit() {
	this.service.getPosts()
	.subscribe(data => this.posts = data)
}
  • If the error is not thrown, error is handled here and will not hit global error handler
createPost
	.subscribe(successCallback, (error: AppError) => {
		if(error instanceOf BadRequest) {
			alert("Bad Request")
		}
		else
			throw error;
	})
  • To simulate unhandled expection use invalid url