JavaScript try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.
The “try… First, the code in try {...} is executed. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch . If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err) .
I'd check out window.onerror
Example:
window.onerror = function(message, url, lineNumber) {
//save error and send to server for example.
return true;
};
Keep in mind that returning true will prevent the firing of the default handler, and returning false will let the default handler run.
If your website is using Google Analytics, you can do what I do:
window.onerror = function(message, source, lineno, colno, error) {
if (error) message = error.stack;
ga('send', 'event', 'window.onerror', message, navigator.userAgent);
}
A few comments on the code above:
Once the code is in place, this is how you view your users' Javascript errors:
Behavior
section and then the Top Events
report.window.onerror
in the list.Secondary dimension
button and entering Event Label
in the textbox that appears.Don't try to use third party services instead try for your own.
The Error Handlers can catch the below scenarios,
To Catch Javascript Errors:
window.addEventListener('error', function (e) {
//It Will handle JS errors
})
To Capture AngularJS Errors:
app.config(function ($provide) {
$provide.decorator('$exceptionHandler', function ($delegate) {
return function (exception, cause) {
//It will handle AngualarJS errors
}
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With