admin管理员组

文章数量:1333476

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?

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?

Share Improve this question edited Apr 26, 2010 at 21:52 Ben Blank 56.7k28 gold badges132 silver badges163 bronze badges asked Apr 26, 2010 at 21:33 Robert HurstRobert Hurst 9,1028 gold badges44 silver badges66 bronze badges 4
  • 2 I can figure out how ... Do you mean can't? – SLaks Commented Apr 26, 2010 at 21:35
  • I think he really meant 'can', he says he already knows how to drop messages to the console – Marcel Korpel Commented Apr 26, 2010 at 21:45
  • I meant can't sorry guys – Robert Hurst Commented Apr 26, 2010 at 21:46
  • jsbin. actually shows JavaScript errors and console output in a div. I'm still not sure how it works, though. – Anderson Green Commented Feb 25, 2013 at 17:37
Add a ment  | 

3 Answers 3

Reset to default 6

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

Custom defined JavaScript errors are output with the throw mand. If you want to input those errors into a div then use the innerHTML method instead of throw and immediately return from the executing function.

konsole = document.createElement('ul');
konsole.id = 'console';
document.getElementsByTagName('body')[0].appendChild(konsole);

    function log(konsole, message, level)
    {
        if (undefined === level) level = 0;
        messageElem = document.createElement('li');
        messageElem.className = 'level-' + level;
        messageElem.innerHTML = message;
        konsole.appendChild(messageElem);
    };


document.getElementById('console')

log(document.getElementById('console'), ': )');

Then it's just about CSS...

本文标签: Is it possible to dump JavaScript errors to a div in HTMLStack Overflow