How do I get a simple stacktrace js example working? - javascript

I'm trying to get a very simple stacktrace.js example working. I'm trying to utilize the printStackTrace() method to do so.
Basically, I'm calling a buggy function that throws an error and a stack trace in the console. However, I want this error and stack trace displayed in the console stored inside a string and get that string printed instead.
For example if I run this function
function foo() {
var x = y;
}
I get an uncaught reference error y is not defined
I need this stored inside a string instead.
So far, I've tried the following
var error = null;
function foo(){
try {
var x = y;
} catch(e) {
error = printStackTrace(e);
}
}
foo();
console.log(error);
But it's printing a different stacktrace that I don't understand.
What's the correct way to use the printStackTrace method?

Try something like,
window.onerror = function(msg, file, line, col, error) {
var callback = function(stackframes) {
var stringifiedStack = stackframes.map(function(sf) {
return sf.toString();
}).join('\n');
alert('msg: ' + msg + ' line: ' + line + ' col: ' + col + ' error: ' + error + ' file:' + file);
};
StackTrace.get().then(callback)
};
Working Example:
window.onerror = function(msg, file, line, col, error) {
StackTrace.fromError(error).then(callback).catch(errback);
}
var errback = function(err) { console.log(err.message);
};
var callback = function(stackframes) {
var stringifiedStack = stackframes.map(function(sf) {
return sf.toString();
}).join('\n'); };
function fault() {
alert('Error will be invoked!')
throw "Test Error"
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stacktrace.js/2.0.0/stacktrace.js"></script>
<input id="a" type="button" value="Test Call!" onClick="fault();" />
but it seems that they have a bug.

If you're using stacktracejs 1.x and can't get it working, this is how you use it:
console.log( StackTrace.getSync() );
That's all.

Related

How to find line where exception occursin javascript in browser

ASP.NET MVC4 shoping cart application implements error logging from client browser using
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
$.post('/Home/Error',
{
"errorMsg": errorMsg,
"url": url,
"lineNumber": lineNumber,
"column": column,
"errorobj": JSON.stringify(errorObj)
});
This logs strange errors about token o :
Error Uncaught SyntaxError: Unexpected token o
urls and column numbers vary a bit:
Line 1 Column 2
Line 1 Column 10 Object {}
Line 1 Column 10 Object {}
Line 1 Column 9 Object {}
Line 1 Column 1 Object {}
Line number is 1 always, object is empty.
There are 4 different column numbers: 1,2,9,10
How to find line in javascript which causes this exception ?
Exception occurs in client browser where there is no access. Only way is to
send information about js code line to browser.
Those pages contain few ajax calls. /Store/Browse contains ajax to add item to cart:
request = $.post('/Store/AddToCart',
serializedData, function (response) {
$("#cart-status").text(response.Total);
$inputs.prop("disabled", false);
var xx = $form[0].quantity;
$($form[0].quantity).css("background-color", "green");
showMessage(response.Message);
showFadeOutMessage(response.Message);
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert('Error ' + textStatus);
})
.always(function () {
$inputs.prop("disabled", false);
});
It is possible to add lastLine assignments to code like
var lastLine;
lastLine="request = $.post('/Store/AddToCart";
request = $.post('/Store/AddToCart',
serializedData, function (response) {
lastLine='$("#cart-status").text(response.Total)';
$("#cart-status").text(response.Total);
lastLine='$inputs.prop("disabled", false)';
$inputs.prop("disabled", false);
...
and send lastLine value to server in window.onerror but this requires lot of code changes manually.
Is there a better way to find line here error occurs and maybe stack trace also ?
window.onerror is different between IE, Chrome and Firefox. Your code will work in IE. This code will work in IE and chrome.
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
$.post('/Home/Error',
{
"errorMsg": errorMsg,
"url": url,
"lineNumber": lineNumber,
"column": column,
"errorobj": errorObj ? errorObj.stack : ''
});
In Chrome errorObj contains three properties: name, stack and message- but all are getter. JSON.parse doesn't handle functions and getter is a function.
For example (Chrome only!)
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
console.log(JSON.stringify(errorObj)); // {}
console.log(errorObj.stack); //SyntaxError: Unexpected token o
// at Object.parse (native)
// at foo (http://www.example.com/index.js:8:10)
// at ...
console.log(errorObj.message); // Unexpected token o
console.log(errorObj.name); // SyntaxError
}
In IE errorObj it's simple object. But errorObj.stack is clearer.
Firefox does not send errorObj argument. You need wrap the code with try catch (or override JSON.parse and wrap the call with try catch), and send e.toString() and e.stack. For example:
var bckJSON = JSON.parse;
JSON.parse = function () {
try {
bckJSON.apply(argumetns};
} catch (e) {
// send e.toString() + '\n' + e.stack
}
}
Sorry about previous non-useful answers...
The error 'Error Uncaught SyntaxError: Unexpected token o' is occur when you invoke JSON.parse with object.
Probably this code happens -
JSON.parse({});
JQuery, in some cases, use $.parseJSON to convert ajax queries without check if the data is string. I don't know when this happens.
You can workaround in this way:
(Use $.parseJSON because it handle browser without JSON library)
JsonParseFix.js
function isString(value) {
return Object.prototype.toString.call(value) === "[object String]";
}
var bckJSONparse = $.parseJSON;
$.parseJSON = function(text, reviver) {
if (!isString(text)) {return text};
bckJSONparse.apply(arguments);
};
test.js
function test(value, message) {
try {
$.parseJSON(value);
console.log('Test succeed: ' + message);
} catch (e) {
alert('Test failed: ' + message);
}
}
test({}, 'Empty object');
test('<', 'UnSupported strings'); // Failed!
Angular solve this in a similar way (angular.fromJson documentation).
(Sorry about my english...)
Based on Elad's andwer and comments I created the following method which returns call stack in IE, Chrome and FireFox:
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
var stack;
// Firefox does not send errorObj argument. Wrap the code with try catch
// and send e.toString() and e.stack.
try {
stack = errorObj ? errorObj.stack : '';
} catch (e) {
stack = e.toString() + " stack " + e.stack;
}
$.ajax('/api/errorlog?' + $.param({
errorMsg: errorMsg,
url: url,
lineNumber: lineNumber,
column: column
}),
{
data: JSON.stringify({ stack: stack }),
type: 'POST',
dataType: 'json',
contentType: "application/json"
});
alert(errorMsg + ' Line ' + lineNumber + ' Column ' + column + '\n\n' + stack);
};

Node node-csv-parse gives "has no method 'join'" error

Can't seem to get the pipe function working properly as I am getting a "TypeError: Object # has no method 'join'" error. My input file is a very basic comma delimitated csv, nothing too fancy.
I'd like to pipe the output directly to my response.
var output = [];
var parser = parse({auto_parse: true, columns: true});
var input = fs.createReadStream('./uploads/' + req.body.file);
var transformer = transform(function (record, callback) {
setTimeout(function () {
callback(null, record.join(' ') + '\n');
}, 500);
}, {parallel: 10});
transformer.on('error', function (err) {
res.send(500,err);
console.log(output);
});
transformer.on('finish', function () {
console.log('finish');
console.log(output);
});
input.pipe(parser).pipe(transformer).pipe(process.stdout);

Generating and saving a list of ParseObjects within a Parse.Cloud.httpRequest in a cloud function

So, I'm defining a cloud function that's supposed to make a call to the foursquare api and generate a list of restaurants (each restaurant is a ParseObject) from the returned JSON. I successfully do this, but I run into problems when trying to save these objects to my database and send them back to my phone by calling response.success(). The large code block below saves the list to my database, but if I try
Parse.Object.saveAll(restaurants)
response.success(restaurants)
I end the function before all of the restaurants are saved. I tried using this line instead
Parse.Object.saveAll(restaurants).then(response.success(restaurants))
, but only half of the restaurants get saved before I get the error "Failed with: Uncaught Tried to save an object with a pointer to a new, unsaved object." I also get this error if I call response.success(restaurants) without attempting to save the list. I read that this is a bug in parse preventing someone from printing or passing unsaved ParseObjects. Any ideas? I also tried using .then on the http request, but I get the same issues or a new error: "com.parse.ParseException: i/o failure: java.net.SocketTimeoutException: Read timed out. "
Parse.Cloud.define("callFourSquare", function(request, response) {
//The Parse GeoPoint with current location for search
var geo = request.params.location;
var geoJson = geo.toJSON();
var url = "https://api.foursquare.com/v2/venues/explore?ll=" + geoJson.latitude + ","
+ geoJson.longitude + "&section=food&sortByDistance=1&limit=50&venuePhotos=1&categoryId=4d4b7105d754a06374d81259&client_id= C043AJBWKIPBAXOHLPA0T40SG5L0GGMQRWQCCIKTRRVLFPTH"
+ "&client_secret=Y1GZZRHXEW1I3SQL3LTHQFNIZRDCTRG12FVIQI5QGUX0VIZP&v=20140715";
console.log(url);
//Call to FourSquare api, which returns list of restaurants and their details
Parse.Cloud.httpRequest({
method: "GET",
url: url,
success: function (httpResponse) {
var restaurants = [];
var json = httpResponse.data;
var venues = json.response.groups[0].items;
console.log(venues.length)
for(i = 0; i < venues.length; i++) {
venue = venues[i].venue;
var RestaurantObject = Parse.Object.extend("Restaurant");
var rest = new RestaurantObject();
try {
rest.set("geoLocation",
new Parse.GeoPoint({latitude: venue.location.lat,
longitude: venue.location.lng}));
} catch(err) {}
try {
rest.set("address", venue.location.address + " " + venue.location.formattedAddress[1]);
} catch(err) {}
try {
rest.set("phoneNumber", venue.contact.formattedPhone);
} catch(err) {}
try {
rest.set("website", venue.url);
} catch(err) {}
rest.set("name", venue.name);
rest.set("lowerName", venue.name.toLowerCase());
try {
rest.set("priceLevel", venue.price.tier);
} catch(err) {}
try {
rest.set("rating", venue.rating/2);
} catch(err) {}
try {
rest.set("storeId", venue.id);
} catch(err) {}
try {
rest.set("icon", venue.photos.groups[0].items[0].prefix + "original"
+ venue.photos.groups[0].items[0].suffix)
} catch(err) {}
restaurants.push(rest);
}
Parse.Object.saveAll(restaurants);
},
error: function (httpResponse) {
response.error("Request failed with response code:" + httpResponse.status + " Message: "
+ httpResponse.text);
}
});
});
I believe your issue is that you aren't returning the Promise from Parse.Object.saveAll(restaurants) when your httpRequest() is complete. Try returning that saveAll() promise and see if it completes.

Easyui - SyntaxError: missing ) in parenthetical

based on that a link!, I'm trying adapt this code to my project. however when I click save this error appears:
SyntaxError: missing ) in parenthetical Warning: main(): It is not
safe to rely on the system's timezone se
My js
function saveItem(index) {
var row = $('#dgusu').datagrid('getRows')[index];
var url = row.isNewRecord ? 'app/cadusuarios_acao.php?opcao=C' :
'app/cadusuarios_acao.php?opcao=A?id=' + row.id;
$('#dgusu').datagrid('getRowDetail', index).find('form').form('submit', {
url: url,
onSubmit: function () {
return $(this).form('validate');
},
success: function (data) {
data = eval('(' + data + ')');
data.isNewRecord = false;
$('#dgusu').datagrid('collapseRow', index);
$('#dgusu').datagrid('updateRow', {
index: index,
row: data
});
}
});
}
Someone can tell me where I am going wrong?
Thanks

js exception position

For the JavaScript code like this:
try {
MyJob.process();
} catch(e) {
console.log("Exception occur!");
}
I run the code in Chrome or FireFox, When the exception happens, the line number of "Exception occur!" will be shown in console, but the original exception in MyJob won't be there. Is there any solution that show the original position where the exception happens and keep the try-catch that I write here?
window.onerror = function ( msg, url, num ) {
alert ( "Error: " + msg + "\nURL: " + url + "\nLine: " + num );
return true;
};
This will show most of the errors.
In the catch block add:
catch(e) {
console.log( e.name + ": " + e.message );
}
More about the error handling at JavaScriptkit
If the try/catch block is inside a function you could take advantage of the arguments.callee mdn msdn
function foo() {
try {
someFunction();
}
catch (e) {
var f = arguments.callee.toString().substr ( "function ".length);
f = f.substr(0, f.indexOf('('));
alert ( "Error type : " + e.name + "\nError : " + e.message + "\nIn function : " + f );
}
}
Result will be:
Error type : ReferenceError
Error : someFunction is not defined
In function : foo
Temporary comment out the try and catch, then step through with the Chrome (or Firefox) JavaScript debugging tools.
//try {
MyJob.process();
/*} catch(e) {
console.log("Exception occur!");
}*/
After identifying the issue, remove the comments to restore the original error handling.

Categories