admin管理员组文章数量:1416642
How can I prevent the script from stopping after an error has been thrown? Is there something like exception handling in JS?
Console text
Not allowed to load local resource: file:///C:/Users/Temp/image.png
How can I prevent the script from stopping after an error has been thrown? Is there something like exception handling in JS?
Console text
Not allowed to load local resource: file:///C:/Users/Temp/image.png
Share
Improve this question
asked Apr 13, 2014 at 19:45
poppelpoppel
1,5934 gold badges17 silver badges22 bronze badges
2
- 1 Add the code that throws the error to your question. – mzedeler Commented Apr 13, 2014 at 19:47
- try/catch usually works, like you'd expect, but there are some errors which you can't catch because they are triggered by other events (e.g. when loading a bad resource as in your example, the error is only known about after the javascript part has finished executing). But in those cases, it won't stop the script anyway (it just logs a warning which you can't avoid). – Dave Commented Apr 13, 2014 at 19:49
4 Answers
Reset to default 5Javascript does have exception handling. There are two possible types of error you can encounter:
1) Places in your application where you proactively guard against errors being thrown, for example, AJAX request. You can handle them like this:
try {
AJAX-code or other code susceptible to errors
} catch(error){
// Log error
}
2) Script errors or pile-time error, for example, undefined variables. In browsers, window.onerror is a global event handler which is called on script or pile errors. However, it's implementation is inconsistent across browsers. You can use it like this:
window.onerror = function(message, url, lineNo) {
// Code to handle the error
}
The main problem with onerror is that no stack trace is passed through which is not very helpful. However, Chromium has added column number and errorObj, so hopefully other browsers will implement the same in near future.
There surely is: try {} catch (exception) {}
Sure, wrap your code inside try/catch:
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
You can use a try
/catch
/finally
block to handle errors:
try {
// Whatever you need
} catch(error) {
// Handle error if one occurs
} finally {
// Last resort
}
Note that you can have multiple catch
blocks in-between your try
and finally
as needed.
Here's some more information.
本文标签: javascriptJShow to prevent script from stopping after thrown errorStack Overflow
版权声明:本文标题:javascript - JS - how to prevent script from stopping after thrown error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745255611a2650081.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论