JavaScript suppress a specific error

2019-08-11 09:06发布

问题:

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)