用 return "console.error" 代替 "undefined" 安全吗?

Is it safe to return "console.error" instead of "undefined"?

我有一段代码如下所示:

// very important checks:
if (blah_blah_blah === true) {
  console.error("Whoops! Something went wrong!");
  return undefined;
}

/*
 * carry on doing things...
 */

// more important checks:
if (blah_blah_blah_blah === true) {
  console.error("Whoops! Something else went wrong!");
  return undefined;
}

/*
 * carry on doing more things...
 */

return undefined; 部分似乎是多余的,因为我可以做到 return console.error("...");,我已经尝试过并且 似乎 也可以工作。

我已经尝试在 MDN 上查看 console.error() 官方 return 的内容,但未能找到任何相关信息。

我也尝试在我的控制台中通过 Node.js 检查 return,输出是:

> console.error("Hello World!")
Hello World!
undefined
> 

我的问题是; return console.error 的 return 值而不是 undefined 是否安全?

谢谢。

比 return 打 console.error 你应该 return new Error("Error message").

并在调用 return 导致此错误的函数后记录一次错误。

function someFunction() {
   // very important checks:
   if (blah_blah_blah === true) {
     return new Error("Whoops! Something went wrong!");
   }

   /*
    * carry on doing things...
    */

   // more important checks:
   if (blah_blah_blah_blah === true) {
     return new Error("Whoops! Something else went wrong!");
   }

   /*
    * carry on doing more things...
     */
 }
 let returnValue = someFunction()
 if(returnValue instanceof Error) {
    console.error(returnValue)
 }

没关系,但不是一个好的做法。

console.error 是一个依赖于实现的函数(它甚至不是 ECMAScript 标准的一部分),所以它的 return 值也是未知的。但是,(据我所知)它在主要浏览器和 Node.js.

中都是 returns undefined

所以这三个可以说是相等的:

return console.error('Oops')
console.error('Oops')
return undefined
console.error('Oops')
return

虽然有效,但效果不佳

记录错误不应取代异常抛出机制。

下面的好多了:

throw new Error('Oops')

为什么?

  • 抛出异常也会停止调用者的执行,除非处理得当。
  • 调用者代码无法阻止日志记录即使它知道如何处理错误。这可能令人困惑。
  • 如果错误未得到处理,错误和堆栈跟踪仍会打印到控制台。

我已经详细解释过了