0

I'm pretty new to JavaScript.

I'm trying to define my custom errors, but it doesn't seems to be working

function MyError(msg){
    this.message = msg
    this.name = "My Error"
}

window.onload = function(){
    try{
        throw new MyError("Test Message");
    } catch(e) {
        alert(e.name + ": " + e.message);
    }
}

Getting TypeError, claiming that it's not a function.

Edited by ultimatebuster: n/a

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by ultimatebuster
0

To what do you intend "this" to refer to in the body of MyError()? When using "this", it is usually a direct reference to the workable object itself, but unless MyError is a method of a class, it is not in an object context.

Instead, do something like:

function MyError(msg)
	{
	myObj = new Object;
	myObj.message = msg;
	myObj.name = "My Error";
	}

It is also considered good practice to always end every statement with a semicolon.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.