I know this has probably been asked before, but I can't find where:
I know you can detect JS errors using extensions in stuff, but is there any way to detect ALL errors using JavaScript and display an alert whenever there is one?
In the browser define the window.onerror function. In node attached to the uncaughtException event with process.on().
This should ONLY be used if your need to trap all errors, such as in a spec runner or console.log/ debugging implementation. Otherwise, you will find yourself in a world of hurt trying to track down strange behaviour. Like several have suggested, in normal day to day code a try / catch block is the proper and best way to handle errors/exceptions.
For reference in the former case, see this (about window.error in browsers) and this (about uncaughtException in node). Examples:
Browser
window.onerror = function(error) {
// do something clever here
alert(error); // do NOT do this for real!
};
Node.js
process.on('uncaughtException', function(error) {
// do something clever here
alert(error); // do NOT do this for real!
});
For JS in Browser
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var lastErr;
function errHand(e) {
lastErr = e;
switch (e.target.nodeName) {
case 'SCRIPT':
alert('script not found: ' + e.srcElement.src);
break;
case 'LINK':
alert('css not found: ' + e.srcElement.href);
}
return false;
}
window.onerror = function (msg, url, lineNo, columnNo, error) {
alert(msg + ' - ' + url + ' - ' + lineNo + ' - ' + columnNo);
return false;
}
</script>
<script src="http://22.com/k.js" onerror="errHand(event)"></script>
<link rel="stylesheet" href="http://22.com/k.css" onerror="errHand(event)" type="text/css" />
</head>
<body>
<script>
not_exist_function();
</script>
</body>
</html>
This works for attached js files trace errors just in same origin host environment
For Request error handeling like Ajax/WebSocket its better use their Bulit-In functions
Console functions override not work for reading auto generated browser error logs at this time with latest browser updates
For NodeJS
process.on('uncaughtException', function (err) {
console.error('uncaughtException:\n' + err.stack + '\n');
})
Use Both of them in the TOP of your codes
Related
I'm trying to detect when a console error occurs. I've looked here and have seen 2 suggestions
window.onerror
and
try catch
The following demonstrates an issue where this is not "caught" (by caught, as per the code below, I'd expect to see an alert and I do not).
window.onerror = function(error) {
alert("window error..." + error );
}
const arr = [];
try{
arr.push({
'firstValue':'Me 'And' You',
'otherValue':5
});
}catch(err){
alert("Error..." + err);
}
The part causing the issue is
'firstValue':'Me 'And' You',
The reason for this is how this line of code is generated and I suspect the real fix is to correct this (using MVC.NET Razor)
'firstValue': '#Model.MyStringWithNoFormattingOrChecking'
Where the value of MyStringWithNoFormattingOrChecking is Me 'And' You
However, my question is about why the onerror or try catch didn't work. Or what I could have done to have caught this using javascript (I don't actually show an alert, I log via Ajax)
Try putting the onerror code in its own script tag, which runs earlier than this syntax error.
This code does what you want
<head>
<script type="text/javascript">
window.onerror = function(error) {
alert("window error..." + error );
}
</script>
<script type="text/javascript">
const arr = [];
try{
arr.push({
'firstValue':'Me 'And' You',
'otherValue':5
});
}catch(err){
alert("Error..." + err);
}
</script>
</head>
[tested in Firefox, Chome and Edge]
I'm running the following script with phantomjs:
var casper = require('casper').create();
var url = 'https://itunesconnect.apple.com/itc/static/login?view=1&path=%2FWebObjects%2FiTunesConnect.woa%3F'
casper.on("page.error", function(msg, trace) {
this.echo("Error: " + msg, "ERROR");
this.echo("file: " + trace[0].file, "WARNING");
this.echo("line: " + trace[0].line, "WARNING");
this.echo("function: " + trace[0]["function"], "WARNING");
errors.push(msg);
});
casper.start(url, function(){
casper.wait(7000, function(){
// casper.echo(casper.getHTML());
})
})
casper.run(function() {
if (errors.length > 0) {
this.echo(errors.length + ' Javascript errors found', "WARNING");
} else {
this.echo(errors.length + ' Javascript errors found', "INFO");
}
casper.exit();
});
Until a few days ago I could access the page which loads an iframe that contains 2 form fields, to allow user login.
Now I get the following error:
Error: Error: undefined is not a constructor (evaluating '$stateParams.path.startsWith('/')')
at setupDSiFrame (https://itunesconnect.apple.com/itc/static-resources/controllers/login_cntrl.js?cache=111920151100:99:46)
at https://itunesconnect.apple.com/itc/static-resources/controllers/login_cntrl.js?cache=111920151100:19:37
at $digest (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:13:11750)
at $apply (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:13:13237)
at f (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:12:56414)
at r (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:12:65848)
at onreadystatechange (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:12:66409)
file: https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100
line: 12
The page loads fine using slimerjs as the engine, but when using slimerjs the login form does not get filled in because the window is not in focus.
I believe this is an issue where casper is using an old version of WebKit and chokes on loading the page. How would I fix this?
Too late to solve the problem but maybe useful for future reference if somebody finds the question searching for a problem with startsWith in PhantomJS (as I did): startsWith method was added on the ECMAScript 6 specification, which is not supported by PhantomJS.
A good polyfill for this is mathiasbynens/String.prototype.startsWith
I'm developing a music app and if I were to go onto the page where you can play sounds, leave that page and then immediately revisit I get this error.
I've googled the problem and I can't seem to find anything similar at all.
I'm using the cordova media player and LowLatencyAudio plugin for my application.
Below is the code on the specified page and an image of the error I receive.
Any help would be greatly appreciated as I'm well and truly stuck!
<div class="drum" id="bass" ontouchstart="play('bass');" ontouchend="touchEnd(event);">Bass</div>
<div class="drum" id="highhat" ontouchstart="play('highhat');" ontouchend="touchEnd(event);">High Hat</div>
<div class="drum" id="snare" ontouchstart="play('snare');" ontouchend="touchEnd(event);">Snare</div>
<div class="drum" id="bongo" ontouchstart="play('bongo');" ontouchend="touchEnd(event);">Bongo</div>
<script type="text/javascript">
var lla;
function onBodyLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
if( window.plugins && window.plugins.LowLatencyAudio ) {
lla = window.plugins.LowLatencyAudio;
lla.preloadFX('assets/bass.mp3', 'assets/bass.mp3', function(msg){}, function(msg){ alert( 'Error: ' + msg ); });
lla.preloadFX('assets/snare.mp3', 'assets/snare.mp3', function(msg){}, function(msg){ alert( 'Error: ' + msg ); });
lla.preloadFX('assets/highhat.mp3', 'assets/highhat.mp3', function(msg){}, function(msg){ alert( 'Error: ' + msg ); });
lla.preloadFX('assets/bongo.mp3', 'assets/bongo.mp3', function(msg){}, function(msg){ alert( 'Error: ' + msg ); });
}
}
function play(drum) {
document.getElementById(drum).className = 'drum touched';
lla.play('assets/' + drum + '.mp3');
}
function touchEnd(event) {
event.target.className = 'drum';
}
</script>
Error: A reference already exists for the audio id.
It looks like it is having an issue with lla.preloadFX being called for the same asset more than once. After reading the plugin doc, and the actual java code, This error is real a warning/notice and not an error. I have reformatted my example to show how I would ignore this message as it will not affect your application.
Here is an example:
function onDeviceReady() {
if( window.plugins && window.plugins.LowLatencyAudio) {
lla = window.plugins.LowLatencyAudio;
lla.preloadFX('assets/bass.mp3', 'assets/bass.mp3', function(msg){}, function(msg){ if(msg != 'A reference already exists for the specified audio id.') { alert( 'Error: ' + msg ); } });
}
}
Using this code, you will see an error if there is a 'real' error, otherwise it will ignore the message about the resource already being loaded. This should resolve the issue.
actually deviceready event call function lla.preloadFX whenever you start the Application and preloadFx() try to load asset again those already loaded. so you can unload the assets on application exit by just handling backbutton event.
function onBodyLoad() {
document.addEventListener("backbutton", onBackButton, false);
}
function onBackButton() {
var assets=['bass','snare','highhat','bongo'];
for (x in assets) {
lla.unload(assets[x], function (msg) {}, function (msg) {});
}
navigator.app.exitApp();
}
window.onerror = function(type, file, line){
if(type) {
console.log(type);
}
if(file) {
console.log(file);
}
if(line) {
console.log(line);
}
}
this code returns "Script error" when there is an error at some of the .js files. I need the type, file and line of the error. How can I get it?
When window throws error this script works perfect but it is not the same when there is error in the .js file.
I know that these things I can find on the console but imagine that I don't have one and i cannot install.
window.onerror = ErrorLog;
function ErrorLog (msg, url, line) {
console.log("error: " + msg + "\n" + "file: " + url + "\n" + "line: " + line);
return true; // avoid to display an error message in the browser
}
The post of Cryptic "Script Error." reported in Javascript in Chrome and Firefox should answer your "Script Error." problem. Namely it is probably caused by "Same origin policy".
Though I am still looking for why webkit will give me "undefined" file name and "0" line number for uncaught exception.
Here's what I use to capture errors. I have it request an image whose url points to a server side script.
function logJSErrors(errObj) {
if (!errObj || !errObj.lineNumber || errObj.lineNumber == 0) {
return; // can't use it any way.
}
if (window.location && window.location.toString().indexOf('rfhelper32.js') >= 0) {
return; // ignore the stupid Norton/Firefox conflict
}
var img = new Image();
img.src = "/jserror?m=" + encodeURIComponent(errObj.message) +
"&location=" + encodeURIComponent(window.location) +
"&ln=" + encodeURIComponent(errObj.lineNumber) +
"&url=" + encodeURIComponent(errObj.fileName) +
"&browser=" + encodeURIComponent(errObj.browserInfo);
}
window.onerror = function (msg, url, line) {
logJSErrors({ message : msg,
lineNumber : line,
fileName : url,
browserInfo : window.navigator.userAgent
});
// if a jquery ajax call was running, be sure to make the spinning icons go away
if (jQuery) {
try {
jQuery.event.trigger("ajaxStop");
} catch(e) {/* do nothing */
}
}
};
On my forum-based website, I have a link below every post for reporting spam or abuse. Whenever this link is clicked, a web service is called on the server, when the call returns, the span containing the link (see the code below) is updated with something like 'Post reported' or if an error occurs it shows something like 'An error occurred while reporting the post', this is the javascript code:
<script src="/js/MicrosoftAjax.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript" language="javascript">
var spanToUpdate;
function ReportPost(updateSpan, postID)
{
if (confirm("Are you sure you want to report this post as spam or abuse?"))
{
spanToUpdate = updateSpan;
var proxy = SiteWS.ReportPost(postID, onReportPostSuccess, onReportPostFailure);
}
}
function onReportPostSuccess(sender, e)
{
spanToUpdate.innerHTML = "Post reported";
}
function onReportPostFailure(sender, e)
{
spanToUpdate.innerHTML = "An error occurred while reporting the post";
}
</script>
And this is the reporting link:
<div class="post">
<p>post text here</p>
<span>Report Post</span>
</div>
Other posts ...
As you can see, I use a variable, spanToUpdate, to hold a reference to the span that contains the reporting link, which means that if the user reports another post (ie. clicks another reporting link) before the call returns, the span of the last post will be updated twice and the previous one won't be updated at all, is there any workaround for this?
Many thanks
You can use anonymous functions and closures for that.function ReportPost(updateSpan, postID) {
if (confirm("Are you sure you want to report this post as spam or abuse?")) {
var proxy = SiteWS.ReportPost(
postID,
function(sender,e) {updateSpan.innerHTML = "Post reported" },
function(sender,e) {updateSpan.innerHTML = "An error occurred while reporting the post" }
);
}
}
edit: hmm .. just wondering, will updateSpan be referring to the same span when the anonymous method is called? – Waleed Eissa
Yes, that's the magic of closures. Try this little example:
<head>
<script>
function foo()
{
bar(1, 100);
bar(2, 150);
bar(3, 200);
bar(4, 250);
bar(5, 300);
document.getElementById("div1").innerHTML += "foo() is done. ";
return;
}
function bar(val, timeout) {
window.setTimeout(
function() {
document.getElementById("div1").innerHTML += " " + val + " ";
},
timeout
);
}
</script>
</head>
<body>
<button onclick="foo()">click</button>
<div id="div1"></div>
</body>You will see that each time the anonymous function is called it has preserved "its own" value of val from the time/context when bar() was called.
Not a JavaScript developer so this might not work. Would it be possible to hold a reference to the post id and the spanToUpdate and then have the response from the server include the post id. Then you could retrieve the correct spanToUpdate.