eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule proposal: Don't log when re-throwing a caught error

Open fregante opened this issue 4 years ago • 2 comments

I don't know if this applies everywhere, but it feels that if you're catching an error just to log it and then throwing it again, you're potentially passing the error to another step that will do the same, resulting in the same error being logged twice.

Alternatives:

  • only log the error in the last step, e.g. log('there was an error', error); exit(1)
  • if your intent is to add more details, create a new Error + Error#cause

Fail

try {
	null();
} catch (error) {
	console.log('Error while doing stuff', error); // Log
	throw error; // and re-throw
}

Pass

try {
	null();
} catch (error) {
	console.log(error); // Only log
}
try {
	null();
} catch (error) {
	doSomething(error);
	throw error; // Re-throw
}
try {
	null();
} catch (error) {
	const specificError = new Error('Error while doing stuff')
	specificError.cause = error
	throw specificError; // Throw new error with more details
}

fregante avatar Oct 01 '21 13:10 fregante

Maybe this could be part of https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1342?

sindresorhus avatar Dec 28 '21 11:12 sindresorhus

Maybe this could be part of #1342?

Potentially, yes, since the solution is:

  • create new error to add more info + use cause; or
  • just drop the log

fregante avatar Apr 01 '22 07:04 fregante