JavaScript抑制特定错误 [英] JavaScript suppress a specific error

查看:70
本文介绍了JavaScript抑制特定错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JavaScript文件中包含以下行,这会在控制台上创建错误消息:

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.

我读到的是 window.onerror ,但是没有用。据我了解,这会禁用页面上的所有错误,但是我只想禁用我行的错误。我试过将它放到右边,但是它也不起作用:

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.

推荐答案

通常来说,这不需要产生错误。您遇到什么错误?那myObject没有定义?如果是这样,只需添加防护措施并检查其是否已定义。例如:

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
}

要查看正在发生的情况,请尝试运行以下代码,并在删除 var myObject = {} 行时查看正在发生的情况。

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)

这篇关于JavaScript抑制特定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆