Billy Moon
Billy Moon

Reputation: 58531

How to retrieve try/catch error

how can I find the error

try {
    undef
} catch (e){
    console.log(e)
    console.dir(e)
}

the information bust be there somewhere, because the console.log (in firebug) includes:

ReferenceError: undef is not defined

but when I browse the e object, I can't find it.

How do I find out what the error is programmatically, so I can handle the error accordingly?

Edit: screenshot showing error object

Upvotes: 0

Views: 3052

Answers (3)

Billy Moon
Billy Moon

Reputation: 58531

But of trial and error gives me this...

try {
    undef
} catch (e){
    console.log(e.toString())
    // ReferenceError: undef is not defined
}

I guess firebug is just accessing the .toString() method of e


Edit:

I am guessing the .toString() method just concatenates the only two properties that are guaranteed cross browser - name and message - so I think e.message is the only reliable and useful piece of information to go with.

Upvotes: 0

RonPringadi
RonPringadi

Reputation: 1494

try {

    if(typeof undef  == 'undefined'){       
        console.log('We should not access this "undef" var');
    }       
    console.log('The next line will produce an exception');
    undef
} catch (e){
    console.log(e);
    for(index in e){
        console.log(index+' ('+(typeof e[index])+'): '+ e[index]);
    }
}

Which will produce:



We should not access this "undef" var
The next line will produce an exception
ReferenceError: undef is not defined
fileName (string): file:///B:/xampp/htdocs/study/test.html
lineNumber (number): 12
stack (string): @file:///B:/xampp/htdocs/study/test.html:12

Upvotes: 1

Dancrumb
Dancrumb

Reputation: 27539

I don't think you can pull its type explicitly, but you can test it:

try {
    undef
} catch (e){
    console.log(e)
    console.dir(e)
    if(e instanceof ReferenceError) {
      console.log("Ooops! Fat fingers!");
    }
}

Upvotes: 0

Related Questions