JavaScript suppress a specific error

怎甘沉沦 提交于 2019-12-13 02:14:30

问题


I have the following line in my JavaScript file, which creates an error message on the console:

myObject.width = 315;

I want to hide this error message on the console. I mean that, this line of code will run, it will give error, but won't display it on the console log.

I read about window.onerror, but it did not work. As I understand, this disables all the errors on a page, however I want to disable the errors of only my line. I tried putting it right after, but it didn't work either:

myObject.width = 315;
window.onerror = function(){
       return true;
    }

Is there any workaround for this? Thanks.


回答1:


Generally speaking this shouldn't need to yield an error. What's the error you're getting? That myObject isn't defined? If so, just add a safeguard and check if it's defined. Such as:

if (myObject) {
    myObject.width = 315
}

That said, you can surpress it by wrapping it in a try-catch

try {
    myObject.width = 315;
}
catch(err) {
    // do nothing
}

To see what's happening, try running the following code and see what's happening when you're removing the var myObject = {} line.

var myObject = {}

try {
    myObject.width = 315;
} catch(err) {
    console.log('error');
}

console.log(myObject)


来源:https://stackoverflow.com/questions/36474344/javascript-suppress-a-specific-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!