Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add properties to JavaScript Error object?

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?

like image 369
Ziv Levy Avatar asked Nov 12 '17 12:11

Ziv Levy


People also ask

Can I add property to object JavaScript?

You can add new properties to an existing object by simply giving it a value.

How do you fix an object object error?

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.

What properties does an error object have?

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.

How do you add properties to an object?

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.


2 Answers

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'
like image 108
Paulooze Avatar answered Sep 21 '22 06:09

Paulooze


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.

like image 42
Chen Peleg Avatar answered Sep 21 '22 06:09

Chen Peleg