Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript error messages, custom object representation

Tags:

javascript

Is there a way in javascript to make the runtime use a different object representation in the error messages.

A typical error message

Uncaught TypeError: Object [object Object] has no method 'toggle'

It would be helpful if we can give a better representation to the object than [object Object] .In other languages you can make it print a better representation of the object by overriding toString().

However it looks like overriding toString has no effect in this case.

like image 390
Ahmed Aeon Axan Avatar asked Nov 09 '13 15:11

Ahmed Aeon Axan


People also ask

How do you make an error message in JavaScript?

In JavaScript error message property is used to set or return the error message. Return Value: It returns a string, representing the details of the error. More example codes for the above property are as follows: Example 1: This example does not contains any error so it does not display error message.

What is custom error in JavaScript?

You can use this error class to construct your own error object prototype which is called as custom error. Custom errors can be constructed in two ways, which are: Class constructor extending error class. Function constructor inheriting error class.

Does JavaScript have an error object?

Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types.


1 Answers

I would use a try...catch and throw your own error messages:

var obj = {
  name: 'obj',
  fn: function () {
    return 'hallo';
  }
}


function hasMethod(obj, fn) {
    try {
        if (!obj[fn]) {
            var err = obj.name + ' does not have a method ' + fn;
            throw new Error(err)
        }
    } catch (e) {
        console.log(e)
    }
}

hasMethod(obj, 'moose'); // obj does not have a method moose

Fiddle

like image 66
Andy Avatar answered Sep 23 '22 10:09

Andy