Handling Runtime errors in Javascript - javascript

I want to handle runtime errors in Javascript. But I'm faced with a problem. When I used to window.onerror function I can get unexception errors. But I'm defining an undefined function inside any defined function. I can't see any exception. Where I am doing a mistake ?
Here is my code that I used;
function errorHandler(message, url, line, column, error) {
debugger
var message = [
'Message: ' + message,
'\nURL: ' + url,
'\nLine: ' + line,
'\nColumn: ' + column,
];
}
window.onerror = errorHandler;
index.html code;
function exceptionTest() {
test();
}
exceptionTest() function is defined in my code. But test function is undefined. I want to get an error about that undefined function. How can I do that ? It is showing only browser's console window.
Thank you for your suggestions.

you can use try catch blocks to catch these errors:
try{
test();
} catch(error){
console.log("Following error happened:", error);
}

Well, I tried below use case where onerror is taken from this MDN Link
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body onload="Test1();">
<script type="text/javascript">
function Test1() {
Test2();
}
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
if (string.indexOf(substring) > -1) {
alert('Script Error: See Browser Console for Detail');
} else {
var message = [
'Message: ' + msg,
'URL: ' + url,
'Line: ' + lineNo,
'Column: ' + columnNo,
'Error object: ' + JSON.stringify(error)
].join(' - ');
//uncomment below line to see the message in console.
//console.log(message);
alert(message);
}
return false;
};
</script>
</body>
</html>
And it shows correct message with the location of the error with line number and column number.
The error information when logged to console is as below:
DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
HTMLPage1.html
HTML1300: Navigation occurred.
HTMLPage1.html
SCRIPT5009: 'Test2' is undefined
HTMLPage1.html (12,13)
Message: 'Test2' is undefined - URL: file:Desktop/HTMLPage1.html - Line: 12 - Column: 13 - Error object: undefined
HTMLPage1.html (29,17)

Related

sapui5 - javascript error handling - without try-catch in every callback

I am developing a SAPUI5-App. Is there a way to show all errors directly to the customer without having to put a try-catch-block into every callback of sapui5? He will use my app in a mobile device and wouldn´t be able to see the log.
I tried already the following code:
<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
return false; //true = suppress error alert
};
window.addEventListener("error", handleError, true);
function handleError(evt) {
if (evt.message) {
alert("error: "+evt.message +" at linenumber: "+evt.lineno+" of file: "+evt.filename);
} else {
alert("error: "+evt.type+" from element: "+(evt.srcElement || evt.target));
}
}
jQuery.sap.log.addLogListener({
onLogEntry : function(oLogEntry) {
if(oLogEntry.level == '1'){
alert(oLogEntry.details + ' - '+oLogEntry.message);
}
}});
</script>
But I like to actually copy the error-message from the log into an alert for the customer, so he can send me screenshots of the error in his device.
All my attempts did not show enough information or didn´t fire on every error in the console-log.

Javascript load file fails without error

When I run this:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
try {
$("#div1").load("demoddd.txt"); //there is no demoddd.txt
}
catch (err)
{
alert("Error: " + err); //this never runs
}
finally {
alert("Finally");
}
});
});
</script></head>
<body>
<button id="btn">Load file</button>
<div id="div1"></div>
</body>
</html>
I get "Finally" but no error. In the debug console, I see the 404. Can I trap 404 errors when using the load() function?
Use the complete function as shown in the documentation:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
You need to get the httprequest status, you can't catch an 404 with that catch.
Use this:
$("#div1").load("/demoddd.txt", function(responseText, statusText, xhr){
if(statusText == "success")
alert("Successfully loaded!");
if(statusText == "error")
alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
});
The first thing I would try is to set the full URL, and not a relative one. See if that works first.

Uncaught ReferenceError: Parse is not defined

I unexpectedly received the following error through the debugger when trying to execute parse.
Uncaught ReferenceError: Parse is not defined
I am pretty sure its well defined so not sure where the error derives from.
Essentially what happens here is that a long url gets converted into a short url using google url shorten and then parse grabs the shorten url and stores it.
<html>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", str);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
<body>
URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output"></div>
</body>
</html>
In particular, below is the conversation happens, and where I try to store the url to parse:
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", str);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
Maybe you have this in another file but where is your code where you reference Parse http://www.parsecdn.com/js/parse-1.3.5.min.js ?
Maybe you are missing that and that's why you get the error.

Syntax error for cross domain messaging

below is my code. I am trying to receive data from a website using cross-domain messaging. When I click the runit button, I keep getting the following error: "Uncaught SyntaxError: An invalid or illegal string was specified." Please help me identify the problem, I am at a loss.
html code:
<html>
<script language="JavaScript">
function runit() {
alert("here");
// Get the iframe window object
var client = document.getElementById('client');
// Create the data string to be passed to the OPS JavaScript
var data = "{'url' : 'http://ops.epo.org/3.0/rest-services/published-data/publication/epodoc/EP1000000/biblio', " + "'method' : 'GET', " + "'requestHeaders' : {'Origin': 'ops.epo.org', 'Accept': 'application/json' } " + "}";
alert(data);
// Use the postMessage() method in order to send the data to the
// iframe object
client.contentWindow.postMessage(data, 'ops.epo.org');
}
// Add event listener for your window
window.addEventListener("message", receiveMessage, false);
// Method handling window events
function receiveMessage(event) {
alert("here");
// Check origin of the event!
if (event.origin == "http://ops.epo.org") {
var dataJSON = eval('(' + event.data + ')');
// work with data / display data
alert(dataJSON);
}
else {
alert("Got message from unknown source.");
}
}
</script>
<body>
<input type="button" onclick="runit()" value="runit"></input>
<iframe width=100 height=100 id="client" src="http://ops.epo.org/3.0/xss/crosssitescript.html" />
</body>
</html>
EDIT:
I tried double quotes for the data string, and JSON.stringify, and it didn't work:
var data = JSON.stringify('{"url" : "http://ops.epo.org/3.0/rest-services/published-data/publication/epodoc/EP1000000/biblio", ' + '"method" : "GET", ' + '"requestHeaders" : {"Origin": "ops.epo.org", "Accept": "application/json" } ' + '}');
You have to pass the protocol of the targetOrigin when you call postMessage:
client.contentWindow.postMessage(data, 'http://ops.epo.org');
This also works, but may have security implications:
client.contentWindow.postMessage(data, '*');
I peeked at the documentation for what you're trying to do, and there's also the option to use JSONP. Why not just use that, since it's simpler and probably better supported?

Error:Domains, protocols and ports must match <br/> Error: "Object [object global] do not have method 'getElementsByTagName'"

I am using NODE JS module with which I am creating a HTTP server. Server's response is a page containing JavaScript which embed a webpage in <iframe> and within this <iframe> I am accessing its elements data with getElementsByTagName.
Here is response code:
<html>
<head>
<script type='text/javascript'>
function test() {
document.body.innerHTML='<iframe id="ifool" src="file:///C:/Users/Naman/Desktop/rew.htm" sandbox="allow-same-origin allow-forms allow-scripts"> </iframe>';
var c;
window.setInterval(function(){
c=document.getElementById("ifool").contentWindow.location.href;
window.history.pushstate(0,0,c);
},100);
window.setInterval(function () {
var x = document.getElementById("ifool");
var y = (x.contentWindow || x.contentDocument);
if (y.document) y = y.document;
try {
var a = y.getElementsByTagName("input")[0].value;
var b = y.getElementsByTagName("input")[1].value;
} catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}, 2000);
</script>
</head>
<body onload= 'test()'>
</body>
</html>
I am getting error here as "Object [object global] do not have method 'getElementsByTagName'". I am using Chrome with this but I also tried Firefox.
In inspect element console I also getting following error-
localhost: Unsafe JavaScript attempt to access frame with URL "URL1" from frame with URL http://localhost:8080/. Domains, protocols and ports must match.

Categories