JavaScript Error Handling
JavaScript error handling can be helpful to help debug code. Although we think we are good enough at programming sometimes we still face errors. These errors can occur due to inattention, not necessarily due to lack of knowledge, because of an erroneous server response or many other reasons for which we lose a lot of time to figure out what's the cause.
Commonly, a script immediately stops in case of an error occurred, printing it into the console.
We are lucky that there is a syntax construct try..catch
that represent the handling of exceptions due to data or coding errors during program execution.
Try..Catch syntax
The try..catch
construct has two main blocks: try
, and then catch
.
try {
// Code to test
} catch (err) {
// Error handling
// If there was an error they are put into an object
// In the case above: 'err' is an object that has multiple
// properties we can pull values off and use.
// Note - error messages will vary depending on browser
}
Workflow:
- First, the code from
try
block is executed. - If there were no errors, then
catch(err)
block is ignored (the execution reaches the end oftry
and then jumps overcatch
). - If an error occurs, then
try
block execution is stopped, and the control flows to the beginning ofcatch(err)
. Theerr
variable (can be named anything) contains an error object with details about what’s happened.
So, if an error occurs inside the try
block, the script will not halt, and we have a chance to handle it in catch
block.
Error object
When an error occurs, JavaScript generates an object containing the details about it. The object is then passed as an argument to catch:
try {
// ...
} catch(err) { // <-- the "error object", could use another word instead of 'err'
// ...
}
The error object inside catch
block has the following properties:
- err.error: the result of the error;
- err.name: type of error (EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError);
- err.message: provides explanation of message;
- err.stack: stack trace of error;
- err.filename: the name of the file where the error is in;
- err.linenumber: the line where the error occurs on.
elmah.io: Error logging and Uptime Monitoring for your web apps
This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.
See how we can help you monitor your website for crashes Monitor your website