Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dump JavaScript errors to a div in HTML?

I'm writing a game and I've got a console for developers to interact with JavaScript methods in the game. I have a problem though; I can't figure out how to drop JavaScript errors to the console. Is there anyway to write errors to a div or HTML element?

like image 309
Robert Hurst Avatar asked Apr 26 '10 21:04

Robert Hurst


People also ask

What errors occur in JavaScript?

Errors are statements that don't let the program run properly. There are three main types of errors that can occur while compiling a JavaScript program: syntax errors, runtime errors, and logical errors.


1 Answers

It sounds like you already have the ability to execute JS working, and just need to capture error output? If so, you should be able to do so by wrapping your execution code in a try ... catch block:

var result;

try {
    result = eval($("#console-input").val());
} catch (ex) {
    if (ex !== null && typeof ex !== "undefined") {
        if (ex.message) ex = ex.message;
    } else {
        ex = "An unknown error occurred.";
    }

    result = ex;
}

$("#console-output").append($("<p/>").text(result));
$("#console-input").val("");

This will add the result of the code to an output div if no error occurs. If an error does occur, it will instead output either the error message (if any) or "An unknown error occurred."

like image 91
Ben Blank Avatar answered Oct 14 '22 12:10

Ben Blank