Dependiendo del marco de nodejs, generalmente hay dos formas de administrar los errores.
throw new Error('invalid id'); )return { 400: 'invalid id' }; )Debido al viejo consejo de que arrojar errores es ineficiente, siempre traté de devolver errores, pero prefiero arrojar errores porque son más convenientes. El único artículo que se refería al impacto en el rendimiento se refería a Node v0.
¿Sigue siendo cierto?
Actualización 1
Nvm, me di cuenta de que podía probarlo yo mismo. El siguiente código es para referencia:
import { performance } from "perf_hooks"; function ThrowException() { throw new Error("invalid exception"); } const _ATTEMPT = 1000000; function ThrowingExceptions() { const p1 = performance.now(); for (let i = 0; i < _ATTEMPT; i++) { try { ThrowException(); } catch (ex: any) { // log error } } const p2 = performance.now(); console.log(`ThrowingExceptions: ${p2 - p1}`); } function ReturnException() { return { error: { _: "invalid exception" } }; } function ReturningExceptions() { const p1 = performance.now(); for (let i = 0; i < _ATTEMPT; i++) { const ex = ReturnException(); if (ex.error) { // log error } } const p2 = performance.now(); console.log(`ReturningExceptions: ${p2 - p1}`); } function Process() { ThrowingExceptions(); ReturningExceptions(); ThrowingExceptions(); ReturningExceptions(); } Process();Resultados
ThrowingExceptions: 15961.33209991455 ReturningExceptions: 5.09220027923584 ThrowingExceptions: 16461.43380022049 ReturningExceptions: 3.0963997840881348Actualización 2
La creación de errores creó la mayor sanción. Gracias @bergi
import { performance } from "perf_hooks"; const error = new Error("invalid exception"); function ThrowException() { throw error; } const _ATTEMPT = 1000000; function ThrowingExceptions() { const p1 = performance.now(); for (let i = 0; i < _ATTEMPT; i++) { try { ThrowException(); } catch (ex: any) { // log error } } const p2 = performance.now(); console.log(`ThrowingExceptions: ${p2 - p1}`); } function ReturnException() { return { error }; } function ReturningExceptions() { const p1 = performance.now(); for (let i = 0; i < _ATTEMPT; i++) { const ex = ReturnException(); if (ex.error) { // log error } } const p2 = performance.now(); console.log(`ReturningExceptions: ${p2 - p1}`); } function Process() { ThrowingExceptions(); ReturningExceptions(); ThrowingExceptions(); ReturningExceptions(); } Process();Resultados
ThrowingExceptions: 2897.1585998535156 ReturningExceptions: 3.7821998596191406 ThrowingExceptions: 2905.3162999153137 ReturningExceptions: 4.0701003074646