2

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.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Faruk Yazici
  • 2,344
  • 18
  • 38
  • Why do you want it to give an error if it's not going to show the error anywhere? Why not just check if `myObject` is set? – Barmar Apr 07 '16 at 11:09
  • I don't want to give the error. I just want to run the code with it's errors, but not show them. – Faruk Yazici Apr 07 '16 at 11:12

1 Answers1

4

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)
Emil Oberg
  • 4,006
  • 18
  • 30
  • This prevents the error, but the line of code does not run eventually. – Faruk Yazici Apr 07 '16 at 11:10
  • @FarukYazıcı What do you expect it to do if there's an error? – Barmar Apr 07 '16 at 11:14
  • @FarukYazıcı The line myObject.width = 315; is very much executed. I updated my answer with an example. See that it logs the updated object? And if you're removing the first var statement - it'll log "error". – Emil Oberg Apr 07 '16 at 11:17