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.
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.
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.
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.
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
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