我都见过:
throw new Error(error);
&
console.error(error);
例如:
jQuery :
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
&
Vue.js :
if (config.warnHandler) {
config.warnHandler.call(null, msg, vm, trace);
} else if (hasConsole && (!config.silent)) {
console.error(("[Vue warn]: " + msg + trace));
}
两种错误处理方式似乎都可靠且有用。但我的问题是:
Is there a difference between them? And if there is, when should I use which?
最佳答案
关键区别: throw 会停止执行,而 console.error
才不是。
大多数时候,最好抛出一个错误。
这是一种内置的方式来表示某些事情失败并且正常执行无法继续,除非错误是预期的、捕获的和正确处理的。
在大多数平台中,未捕获的异常也会记录到控制台以警告开发人员,但捕获的异常不会被记录,因为它们被假定为由代码处理。
使用 console.error
对于发生的错误不是致命的情况可能有好处,但您想警告开发人员。
但是,过度使用此功能很容易导致其他错误和难以调试的代码。例如,考虑以下代码:
const elem = document.querySelector('.elem')
if(!elem)
console.error('elem cannot be found!')
const returnValue = functionThatDoesSomethingWithElem(elem)
if(!returnValue.success)
console.error('Doing something with elem has failed!')
if(!returnValue.doSomethingElse())
console.error('Doing something else with elem has failed!')
如果没有 elem,上面的代码将记录三个错误,但执行仍然继续,可能会导致更多错误。通过抛出异常,这是可以避免的:
const elem = document.querySelector('.elem')
if(!elem)
throw new Error('elem cannot be found!')
const returnValue = functionThatDoesSomethingWithElem(elem)
if(!returnValue.success)
throw new Error('Doing something with elem has failed!')
if(!returnValue.doSomethingElse())
throw new Error('Doing something else with elem has failed!')
这将只打印第一条错误消息,并且执行停止,除非你把它放在 try..catch
中。结构,如:try{
const elem = document.querySelector('.elem')
if(!elem)
throw new Error('elem cannot be found!')
const returnValue = functionThatDoesSomethingWithElem(elem)
if(!returnValue.success)
throw new Error('Doing something with elem has failed!')
if(!returnValue.doSomethingElse())
throw new Error('Doing something else with elem has failed!')
}catch(exception){
console.error(exception)
fallbackMethod()
}
还有另一个区别:
throw
n 错误可以被函数的调用者捕获,因此它可以以编程方式处理它们(导致执行继续,并且不显示错误)。另一方面,如果您使用 console.error
,来电者可以不是 决定是否预期会出现错误,即使错误是正常的也会导致记录错误,因此控制台可能会变得困惑(您无法确定什么是真正的错误,什么不是。
关于javascript - 我应该使用 console.error() 还是 throw new Error(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60383852/