javascripterror-handling

Is there a way to override the default JS error messages?


I'm guessing the answer to my question is no, but since I don't know enough about how Error.prototype works I figured it was worth asking: is there any way to change the error messages from the errors in Javascript?

For instance, if I get an error:

TypeError: (intermediate value) is not iterable

is there any way to change things such that I instead get:

TypeError: You expected an array but it wasn't an array dummy!

I thought about using a global error handler and then rethrowing them, but that would only work for uncaught errors. Is there any Error.prototype method I can change (or any other way) to do this?

Not at all important, just curious.

EDIT: Just to clarify two points:

1) I understand how try/catch works, but what I'm asking about is whether there is a way to control the messages generated before the error is thrown/caught (presumably by overwriting a method of Error.prototype).

2) An answer of "no there is no way to do this, all generating of JS error messages is handled internally and the JS code has no way to control it" would be perfectly legitimate (... if that's the case).


Solution

  • You have to override the TypeError class, not one of these methods.

    const overridableMessages = [{
      search: 'TypeError: (intermediate value) is not iterable',
      replace: 'TypeError: You expected an array but it wasn\'t an array dummy!'
    }]
    
    class TypeError extends window.TypeError {
      constructor (message) {
        super(message)
        overridableMessages.forEach((overridableMessage) => {
          if (this.message === overridableMessage.search) {
            this.message = overridableMessage.replace
          }
        })
      }
    }
    
    window.TypeError = TypeError