javascript - JS - how to prevent script from stopping after thrown error - Stack Overflow

How can I prevent the script from stopping after an error has been thrown? Is there something like exce

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
Add a ment  | 

4 Answers 4

Reset to default 5

Javascript 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745255612a4618936.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信