Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how to display script errors in a popup alert?

I want to display script errors in a popup alert instead of showing them in the browser console.

window.onerror = function() {   var message = /* get error messages and put them here */;   alert(message);   return true; }; 
like image 435
powerboy Avatar asked Apr 09 '10 03:04

powerboy


People also ask

How do you show error messages in JavaScript?

Errors in JavaScript can be displayed without the use of alert boxes but using the alert box is the traditional way to do that. We can show errors with two methods without using the alert box. Syntax: node.

How do I display error message below input field?

To customize the appearance and text of these messages, you must use JavaScript; there is no way to do it using just HTML and CSS. HTML5 provides the constraint validation API to check and customize the state of a form element. var email = document. getElementById("mail"); email.

How do you show errors in a textbox?

I think it's best to just place the error right under the textbox using just plain HTML positioning. The manual positioning using JavaScript is not necessary. Then if you are using JQuery you can show/hide/populate the error message as you wish.


2 Answers

Yes, that is the correct way.

See the reference here:

http://www.javascriptkit.com/javatutors/error2.shtml

And explanation of how to see more details of the error here:

http://www.javascriptkit.com/javatutors/error3.shtml

Their example:

window.onerror = function(msg, url, linenumber) {     alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);     return true; } 

If you wish to display a LIST of errors in a single pop-up, it's trickier.

Since the errors occue 1 by 1, you need to do the following:

  • have window.onerror handler store error details in some array
  • Check that array periodically - either via a timer, or on every N'th call of window.onerror handler, or both.

    When the check happens, process entire array, display contents as desired, and empty out an array

like image 141
DVK Avatar answered Oct 04 '22 14:10

DVK


Just in case someone would like to use it with jQuery:

$(window).on("error", function(evt) {      console.log("jQuery error event:", evt);     var e = evt.originalEvent; // get the javascript event     console.log("original event:", e);     if (e.message) {          alert("Error:\n\t" + e.message + "\nLine:\n\t" + e.lineno + "\nFile:\n\t" + e.filename);     } else {         alert("Error:\n\t" + e.type + "\nElement:\n\t" + (e.srcElement || e.target));     } }); 
like image 42
user1398498 Avatar answered Oct 04 '22 15:10

user1398498