Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify the message of a Javascript Error object?

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.

like image 238
JoeTidee Avatar asked Oct 17 '22 07:10

JoeTidee


1 Answers

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.

like image 84
holmberd Avatar answered Nov 01 '22 12:11

holmberd