admin管理员组文章数量:1434913
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.
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.
Share Improve this question edited Jan 23, 2019 at 13:46 p7adams 6623 gold badges9 silver badges26 bronze badges asked Jan 23, 2019 at 13:38 JoeTideeJoeTidee 26.2k29 gold badges113 silver badges163 bronze badges2 Answers
Reset to default 2It 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.
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.
本文标签: ecmascript 6How to modify the message of a Javascript Error objectStack Overflow
版权声明:本文标题:ecmascript 6 - How to modify the message of a Javascript Error object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745627667a2667072.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论