14

Is there any harm in updating the message of an Error object like this?

const err = new Error('bar');
...
err.message = `foo ${err.message}`;

My objective is to add some useful information to the error message when logging the error.

2 Answers 2

2

It can be useful to add some extra information/breadcrumbs as an exception travels up through your application layers. That said, you are mutating an object, which can be hard to reason about in a large code-base; exceptions management normally being a cross-cutting concern in your application.

Also bear in mind that some libraries will extend the Error class and leave the message property without a setter, making it ready-only.

Sign up to request clarification or add additional context in comments.

Comments

1

I just noticed some harm :-(

On chrome 127.0.6533.17 (but not firefox 127.0.2), after your code, the error object is in a screwy state, in which err.message contains your additional annotation, but printing err does not show it:

const err = new Error('bar');
err.message = `foo ${err.message}`;
console.log("err.message = ",err.message);  // "err.message =  foo bar"
console.log("err = ",err);  // "err =\nError: bar\n    at <anonymous>:1:13"

The above is from chrome. On firefox, it shows "foo bar" in the final message instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.