首页 > 解决方案 > 我应该使用 console.error() 还是 throw new Error()

问题描述

我都见过:

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));
      }

两种错误处理方式似乎都可靠且有用。但我的问题是:

它们之间有区别吗?如果有,我什么时候应该使用哪个?

标签: javascript

解决方案


关键区别: throwing 会停止执行,而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,调用者无法确定是否预期错误,导致即使是正常的错误也会记录下来,因此控制台可能会变得混乱(您无法确定什么是真正的错误,什么不是.


推荐阅读