Part 1 – Error Handling Best Practices in Angular
- Posted by Muthukumar Dharmar
- Categories Angular, Best Practices
- Date June 27, 2020
In this article, we will explore the best approach to handle errors globally in Angular web applications.
Types of Errors
Client-Side
Binding errors, References errors, Type errors and the errors thrown from 3rd party packages, etc.,
Http Error Response
Status Codes: 400, 401, 404, 500, etc.,
Typical Error Handling
A typical way of error handling is to capture errors using the TryCatch block and based on the business requirement it will be logged in client-side on developer console. Or to the server-side database using the logger API endpoint. right!
The below diagram illustrates this approach, see how the component and services are logging the errors on Client & Server side.
Sample code and Demo UI:
Handling Errors in Angular Way
Angular core provides set of objects, that we can extend and handle the errors globally.
ErrorHandler class provides a hook for centralized exception handling and this is the Default implementation for handling errors inside the angular core system.
It captures all the exceptions and prints the error message to the developer console.
For better understanding, I have commented-out the try-catch statement, still angular prints all the unhandled errors in the developer console.
Hope you all understood, how angular handles the error globally using the in-build class ErrorHandler.
The HttpInterceptor class provides a way to intercept and transform/handle the Http Requests & Responses.
SOLUTION:
Client-side errors can be captured by extending the ErrorHandler class and all the exceptions can be handled based on our business need.
Http request & responses can be captured by extending the HttpInterceptor class and then we can handle those exceptions by verifying the HTTP status codes and logging it, based on the business need.