window.onerror and [object Event] - javascript

I have some errorlogging code on my website that saves Javascript errors to a file so later i can look to se if there is problems with my code in some browsers.
Sometimes i get a error message like message:[object Event] url:undefined line:undefined so i dont know where the error accures.
How do i get more info from message when it is [object Event] so i can know what file and line number the error is from.
window.onerror = error;
function error(message, url, line) {
// sometimes message is [object Event]
}
I am thinks something like this.
window.onerror = error;
function error(message, url, line) {
// sometimes message is [object Event]
if (typeof message === 'object') {
message = message
+ ' + '
+ message.url
+ ' + '
+ message.lineno;
}
}
Trying this but i get Uncaught TypeError: Object # has no method 'serialize'
if (typeof message === 'object') {
message = JSON.serialize(message);
}
With JSON.stringify(message) i get Uncaught TypeError: Converting circular structure to JSON
if (typeof message === 'object') {
message = JSON.stringify(message);
}

In the case where you get something like [someting Something] in JS, it usually means that it is an object. You can do a console.log(message) and inspect the contents of the object. It would look like
{
somethingHere : 'data',
anotherHere : 'more data'
}
To access them, you can do it in the dot notation:
theObject.somethingHere //data
In your case, that would be like this, where something is a key from the object.
message.something

On which browser or browsers are you seeing this [Event object] message occurring? One possible way to inspect the contents of the object is:
var messageString = '';
for (var x in message) {
if (messageString) messageString += ', ';
messageString += x + ': ' + message[x];
}
message = '{' + messageString + '}';
If you can give any kind of reproducible test case for this onerror message, including browser versions on which is happens, that would help a lot.

Related

node js why does it collapse object when logged together with string?

I was doing some basic JSON parsing and wondered why node js collapses the objects when it is logged together with string
so for example in the code below, if I go console.log(processedData) it won't collapse the object and show the whole string but if I go console.log('Body: ' + processedData) it collapses the objects and goes [object Object][object Object].... I know how to expand them again using util but I was curious on the logic behind it as I am quite new to node. I think I might be missing out on something.
const http = require('http');
const util = require('util');
var options = {
host: 'http://nodejs.org/dist/index.json'
// host: 'en.wikipedia.org',
// path: '/w/api.php?action=query&list=allpages&apfrom=Imperial&aplimit=500&format=json'
};
var req = http.get('http://nodejs.org/dist/index.json', function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
let body = '';
res.on('data', function(chunk) {
body += chunk;
}).on('end', function() {
let processedData = JSON.parse(body);
console.log('Body : ' + processedData);
console.log(typeof body);
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
When you call
console.log(processedData)
You're passing the entire object to console.log for it to do it's thing. However, when you call
console.log('Body: ' + processedData)
You're passing the result of 'Body: ' + processedData to console.log. The evaluation of this expression causes processedData to be converted to its string representation, which if you haven't defined toString on your object, will just be [object Object], so you see Body: [object Object] being logged.
The simplest way to achieve what you're after is to simply pass them as separate arguments:
console.log('Body: ', processedData)
Maybe we should answer following questions: "If you do the operation like below - what is expected a type of result?"
var myVar = "Body : " + processData;
When js engine tries to evaluate such expression it knows that first parameter of the expression is 'string', so it tries to concatenate the string with another string. How processData become a string? By calling 'toString()' on processData.
To achieve the result you expect, to try to use console.log in that way:
console.log("Body:", processData);
This is because JS type coercion.
In first case you print it as object, but in second, you add it to the string ('Body: ' + processedData) - and according to JS type coercion rules it converts it to string (it concatenates it to string)
You can use util module as you suggested, or to use console.dir({body:processedData},{colors:true,depth:4});

Window.onerror doesn't return info about error

I'm trying to create a custom error handler. I've got the following code to intercept the errors:
window.onerror = function (msg, url, lineNo, columnNo, error) {
console.log("msg: " + msg + "url: " + url + "lineNo: " + lineNo + "columnNo: " + columnNo);
}
Then later in the code I'm trying to console.log a variable that doesn't exist (in order to trigger the error). In the console I'm getting the custom:
msg: Script error.url: lineNo: 0columnNo: 0
And below that the default:
myjsfile.js:517 Uncaught ReferenceError: xyz is not defined(…)
How can I access this information - filename, line number, error message - and add it to my custom message? Thank you!
You really should use try-catch
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
create object with all your variables in try and throw it
try {
throw your_obj;
}
and
catch(e)
{
console.log(e); //will print whatever you made "your_obj" to be
}

Parsing server response with $.parseJSON failed

I've got these two simple functions:
function getBatchSliceInfo(batch_num){
//get the batch slice info for the batch_num
alert('batch num is ' + batch_num); //returns the batch_num correctly
$.getJSON("statistics_batchdb.jsp", {batch_number: batch_num, slice_stats: 'true'}, showTable);
}
function showTable(data){
$("#table_slice_stats").hide();
if(data.error){
console.log("Something went wrong");
}
var jo = $.parseJSON(data);
alert('This JSON object has this many elements: ' + jo.length);
$.each(jo[0], function (i, val){
alert('This i value is' + i );
alert('This val value is' + val);
});
$("#table_slice_stats").show();
}
So I call getBatchSliceInfo on the click of a button and we get the JSON.
The response seems to be correct, so server side I'm alright.
However, I'm not passing that response correctly to showTable. "data" appears to be null because in the console I get the error:
Uncaught TypeError: Cannot read property 'length' of null batch_statistics_new.jsp:274
showTable batch_statistics_new.jsp:274
o jquery-1.7.2.min.js:2
p.fireWith jquery-1.7.2.min.js:2
w jquery-1.7.2.min.js:4
d jquery-1.7.2.min.js:4
I'm sure this is a very simple syntax question but I have no idea what's going on.
check your data
var data= [{slice_name:Nutrion,iteration_zero:.....},{......},{......}]
After convert to json Format.your data become like this,
var data= {[{slice_name:Nutrion,iteration_zero:.....},{......},{......}]} //It not json format.
if you tring to use length property it throwing an exceptions.so,do the same think without parsing into json.

Unable to access vline.Message object with postMessage()

While implementing the vLine API, I came up with a problem. When using the postMessage() method of the vline.Channel class, the message was successfully received by the target user, but the the success callback of vline.Promise object did not return a valid vline.Message object. At least I don't have acess to some of the vline.Message methods, like getChannel() or getCreationTime().
Code:
$channel.postMessage(textMessage)
.done(function (message) {
console.log("Message sending successfull || Message sent to " + message.getChannel().getDisplayName() + " at " + message.getCreationTime());
},
this)
.fail(function (err) {
console.log("Message sending failed || Error Type: " + err.type + " || Error Message: " + err.message);
},
this);
Result (console log):
Message sending failed || Error Type: undefined || Error Message: Object #<Object> has no method 'getChannel'
Is this result of a API change that has not been yet referenced on the vLine Developer site or is there an error on the code?
This was a bug on our end; sorry about that. It should now be fixed.

ToString changes Javascript Object to Undefined

mysqlconnection.query("SELECT userID FROM users_session WHERE userSessionID = '" + SESSION_ID_ESCAPED + "'", function SelectCb (err, rows) {
if (err) {
throw err;
}
else {
console.log(rows[0]);
}
How do I turn row[0] into a string so that the browser can view it?
The console tells me rows[0] = {userID: 2} // This is [object Object] in any sort of transfer.
I used , var TheID = rows[0].toString // TheID is now undefined when console.log'd or sent out.
try:
var TheID = rows[0]['userID'].toString();
try this..
console.log(rows[0].userID);
you will get the userID.

Categories

Resources