Expecting the Unexpected — Best practices for Error handling in Angular
Centralize error handling, track errors, and notify about them
In this article, I write about centralizing Angular error handling. I discuss some of the more common topics such as:
- client-side errors
- server-side errors
- user notification
- tracking errors
I present some code snippets during the way and lastly provide a link to the full example.
Whom should we blame for errors?
Why do we have errors in our applications? Why can’t we write code from specifications that always works?
Ultimately, human beings create software, and we are prone to make mistakes. Some reasons behind errors could be:
- Complexity of application
- Communication between stakeholders
- Developer mistakes
- Time pressure
- Lack of testing
This list could go on and on. With this in mind, the time comes when the unexpected happens, and an error is thrown.
Catch them if you can
To catch synchronous exceptions in the code, we can add a
try/catch block. If an error is thrown inside
try then we
catch it and handle it. If we don’t do this, the script execution stops.
Understandably, this becomes unsustainable very fast. We can’t try to catch errors everywhere in the code. We need global error handling.