I see that according to MDN - Error documentation, the Error
object might have different behavior across different browsers.
I'd like to check what is your opinion regarding adding properties on the default Error
object.
In my specific code, I'd like to tag an Error
object with my own tag name for further use, which means -> adding a property to the object as follows:
const error = new Error('some message')
if(someConditionExist()){
error.__myTag = 'tag1';
}
else {
error.__myTag = 'tag2';
}
//then throwing the error and catch it elsewhere...
I haven't seen any guidelines what are the implications (if any...) of such thing.
Is any of you have any concerns? Have you encountered any issues across different browsers?
You can add new properties to an existing object by simply giving it a value.
To fix this, you can use the JSON. stringify() method to change the object into a string that can be popped up in the browser using the alert() method.
The Error object in all browsers support the following two properties: name: The name of the error, or more specifically, the name of the constructor function the error belongs to. message: A description of the error, with this description varying depending on the browser.
One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.
Well, we could argue wether you should add custom properties to built-in objects, but something like this could work:
class CustomError extends Error {
constructor(tag) {
super();
this.__tag = tag;
}
};
const customError = new CustomError('tag1');
console.log(customError.__tag); // 'tag1'
Event though an old question, Another solution might be, in some cases to add properties "on the fly" with Object.assign()
const error = new Error('some message')
const withTag = Object.assign(error , { __tag: "tag_1"})
Just notice that on on console.error() in some browsers you wont see the additional properties that you added.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With