Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Trigger Error

Question

Is there a way to trigger a custom Javascript error message? In Chrome, I have found console.warn[error,log] for sending messages to the browser. However, this only works in Chrome (and possibly Firefox). This line itself triggers an error in Internet explorer, though.

I'd like to be able to trigger errors that violate the rules of the Javascript function. For example, a function that takes an object as a value expects the object to have an attribute of "dialog". If that attribute doesn't exist, I want to trigger an error message "Modal Window: No dialog id specified."

Context

I am building a PHP class and Javascript class that works together so that programmers of our application can easily create dialog boxes that will be uniform and reliable.


Example Code

try {
    if (!params || !params['dialog']) {
        throw "NoDID";
    }
}
catch (error) {
    if (error == "NoDID") {
        //com.MySITE.js.warn("Modal Window: No dialog id specified.");
        //Trigger custom error message here.
    }
}

I'd like the message to go to the javascript window for easy developer debugging. Just doing "throw" results in "Uncaught Custom Error Message". I don't want the user to see this in anything on the page. I want it available in the js log for developer use.

like image 859
teynon Avatar asked Mar 30 '12 16:03

teynon


People also ask

How can JavaScript cause errors?

Grammatical mistakes, such as missing parentheses or unmatched brackets, are the major causes of syntax errors in JavaScript. For example, when you must use conditional statements to address multiple conditions, you may miss providing the parentheses as required, leading to syntax flaws.

What is trigger error?

Used to trigger a user error condition, it can be used in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()). This function is useful when you need to generate a particular response to an exception at runtime.

What's the difference between throw error (' MSG ') vs throw new error (' MSG ')?

catch statement with having throw Error(). This code will do that the 'msg' error is thrown in the try-block which will be get executed by catch statements. new Error object: It captures several properties of the place where the error happened. It exposes an error event with two parameters name & message.


1 Answers

Use throw:

throw "Deliberate Error!";
like image 76
Jonathon Faust Avatar answered Sep 19 '22 22:09

Jonathon Faust