19

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?

3
  • Sure, that's fine. The only concern might be a property name that could (in the future?) collide with a native one Commented Nov 12, 2017 at 13:23
  • @Bergi - right... of course Commented Nov 13, 2017 at 9:05
  • 2
    Example at MDN: Error#custom_error_types Commented Oct 25, 2022 at 17:07

2 Answers 2

19

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'
Sign up to request clarification or add additional context in comments.

3 Comments

I'm aware of that option, though, I don't have any kind of real extension here. Usually you would extend a class to take its behavior further. Here I have the capability of adding the property already, right?
I don't see much difference to what the OP is doing here, except that class extends Error requires native ES6 support in the environment
I like this approach! I used it and also included a constructor argument for the message value to pass in the super call. I proposed an edit to your answer to include it in the example.
8

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.

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.