Javascript capture errors - javascript

I'm using window.error to try to capture all client side errors.
It's working fine with Javascript errors but It doesn't capture all errors like Network Errors, or AJAX errors.
This is my code (I can't use jQuery, so is not possible to use .ajaxError):
window.onerror = function(messageOrEvent, source, lineno, colno, error) {
console.log("Captured: " + messageOrEvent)
}
This is the result:
Anyone knows a way to capture ALL errors on the client side?
Thanks

Maybe hook over the default request object:
(function(orig){
window.XMLHttpRequest=function(...args){
var instance=new orig(...args);
instance.addEventListener("readyStateChange",function(){
if(instance.status!==200){
throw new Error(instance.status+":"+instance.statusText);
}
});
return instance;
};
})(XMLHttpRequest);

I've found a way. This is my code. I think that this capture all errors.
// JavaScript Errors
window.onerror = function(messageOrEvent, source, lineno, colno, error) {
console.log("Captured: " + messageOrEvent)
}
// 404 FILES
window.addEventListener('error', function(e) {
console.log(e);
}, true);
// AJAX Errors
var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send;
function openReplacement(method, url, async, user, password) {
this._url = url;
return open.apply(this, arguments);
}
function sendReplacement(data) {
if(this.onreadystatechange) {
this._onreadystatechange = this.onreadystatechange;
}
this.onreadystatechange = onReadyStateChangeReplacement;
return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
// CAPTURE HERE.
if(this.status != 200){
console.log(this.responseURL + " " + this.status + " " + this.statusText);
}
if(this._onreadystatechange) {
return this._onreadystatechange.apply(this, arguments);
}
}
window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;

Related

How to cache error net::ERR_CONNECTION_REFUSED on JavaScript Web Socket

I'm working on JavaScript client websocket. Code work fine once I run both server program and my below client javascript.
try {
webSocket = new WebSocket(webSocketURL);
webSocket.onopen = function(openEvent) {
console.log("WebSocket OPEN: " + JSON.stringify(openEvent, null, 4));
};
webSocket.onclose = function (closeEvent) {
console.log("WebSocket CLOSE: " + JSON.stringify(closeEvent, null, 4));
};
webSocket.onerror = function (errorEvent) {
console.log("WebSocket ERROR: " + JSON.stringify(errorEvent, null, 4));
};
webSocket.onmessage = function (messageEvent) {
var wsMsg = messageEvent.data;
console.log("WebSocket MESSAGE: " + wsMsg);
if (wsMsg.indexOf("error") > 0) {
console.log (wsMsg.error);
} else {
console.log (wsMsg);
}
};
} catch (exception) {
console.error(exception);
}
But, I got an error 'net::ERR_CONNECTION_REFUSED' that cached by webbrowser. But my code can not catch this error.
Regarding see error message from this picture https://ibb.co/bHSBw0G. Any advise or guidance would be greatly appreciated, Thanks.
I think ErrorEvent has non enumerable properties (only enumerable being isTrusted getter - not super useful). Try accessing property explicitly by doing something like:
webSocket.onerror = function (errorEvent) {
console.log("WebSocket ERROR: " + errorEvent.message)
}

Changing json on express node.js server

I'm quite new to node.js and web development in general (so if I'm entirely off base and you have good material for me to consume I'd really like to see it).
I'm trying to prototype passing a JSON object back and forth between node.js server and http client. The client side so far looks like:
<script type="text/javascript">
document.getElementById("myBtn").addEventListener("click", passArg);
function passArg() {
console.log("I'm here")
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//var json = JSON.parse(xmlhttp.responseText);
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
}
var data = JSON.stringify({"email":"hey#mail.com","password":"101010"});
xmlhttp.send(data);
get_json();
}
function get_json(){
console.log("getting json");
var xmh = new XMLHttpRequest();
xmh.open("GET", "/playlist/playlist.json", true);
xmh.send();
xmh.onreadystatechange = function() {
if (this.readyState == this.DONE ) {
if (this.status == 200) {
var json = JSON.parse( this.responseText );
console.log(json.email + " "+ json.password + " " + json.access_date);
}
else if (xmh.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
}
}
</script>
And the server side is coded as
app.post("/", function (req, res) {
console.log('Request received');
req.on('data', function (chunk) {
console.log('GOT DATA!');
json = JSON.parse(chunk);
json.access_date = "12.04.17";
write_json(json)
console.log("finished writing- in app_post")
});
console.log("passing all clear to client")
res.writeHead(200);
res.send();
})
function write_json(chunk){
console.log("WHADDUP")
console.log(JSON.stringify(chunk))
fs = require("fs")
var filename = "./public/playlist/playlist.json";
var file = require(filename);
file = chunk;
fs.writeFile(filename, JSON.stringify(file), function(err){
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
}
)
console.log("finished writing - in write_json")
}
On the serverside console the following output is generated
Request received
passing all clear to client
GOT DATA!
WHADDUP
{"email":"hey#mail.com","password":"101010","access_date":"12.04.17"}
module.js:428
throw err;
^
SyntaxError: public/playlist/playlist.json: Unexpected end of input
And on the client side of things the console reads
(index):15 I'm here
(index):41 getting json
(index):45 GET http://localhost:8080/playlist/playlist.json net::ERR_CONNECTION_RESET
From this I read that the asynchronous POST event is sending the all clear to call get_json before the file itself is updated. And it seems the updating of the file on the server side isn't working as well. How do I structure the calls to make the edit quite smooth?
The quick answer is to create a function to call res.send, pass it to your write_json function, and invoke it from inside your writeFile callback.
app.post("/", function (req, res) {
console.log('Request received');
req.on('data', function (chunk) {
...
write_json(json, function() {
console.log("passing all clear to client")
res.writeHead(200);
res.send();
console.log("finished writing")
});
});
});
function write_json(chunk, onFinishedWriting){
...
fs.writeFile(filename, JSON.stringify(file), function(err){
if (err) {
return console.log(err);
}
else {
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
onFinishedWriting();
}
});
}
However when you find yourself writing code like this:
});
});
});
then you are probably in the proverbial "callback hell". I suspect that what you want is to use promises. Here's a question specifically about promises and writeFile that will probably help you.

websocket javascript request for x-lite or Bria soft phone

I'd like create a web application which is communicating with X-lite SIP phone. I found API documentation Click here but I don't understand how should I parsed the data for request. For example GET /status "phone". I know use just simple request as GET /showHistory. Thanks for any advice.
function WebSocketTest(){
var ws = new WebSocket("wss://cpclientapi.softphone.com:9002/counterpath/socketapi/v1");
ws.onopen = function (event) {
//here I dont know how to write xml request from documentation
//for example GET /status "phone"
ws.send('GET /showHistory');
};
ws.onerror = function(error){
console.log('Error detected: ' + error);
}
ws.onmessage = function(messageEvent) {
if (typeof messageEvent.data === "string"){
console.log("received text data from the server: " + messageEvent.data);
} else if (messageEvent.data instanceof Blob){
console.log("Blob data received")
}
};
}
Try using localhost:9002
function WebSocketTest(){
var ws = new WebSocket("wss://localhost:9002/counterpath/socketapi/v1");
ws.onopen = function (event) {
//here I dont know how to write xml request from documentation
//for example GET /status "phone"
ws.send('GET /showHistory');
};
ws.onerror = function(error){
console.log('Error detected: ' + error);
}
ws.onmessage = function(messageEvent) {
if (typeof messageEvent.data === "string"){
console.log("received text data from the server: " + messageEvent.data);
} else if (messageEvent.data instanceof Blob){
console.log("Blob data received")
}
};
}

Javascript: Event inside a function object created with the new keyword

I have a C# COM DLL ("This.That") that has events, which I've tested using JS and they work fine. I'm now trying to wrap all my tested code inside an object. The following example works fine:
var oTest = new Test();
function Test()
{
var oDevice = new ActiveXObject("This.That");
this.CancelOperation = function()
{
try
{
oDevice.CancelOperation();
return "CancelOperation successful.";
}
catch (e)
{
return e.message;
}
};
}
But once I try to add an event to it, it doesn't work. It looks like it's probably bad syntax. I can't find any resources online that explain how this is done.
var oTest = new Test();
function Test()
{
var oDevice = new ActiveXObject("This.That");
this.CancelOperation = function()
{
try
{
oDevice.CancelOperation();
return "CancelOperation successful.";
}
catch (e)
{
return e.message;
}
};
oDevice::DeviceStatusUpdate(wasSuccess, message, data) = function()
{
document.getElementById("outBox").value += "Success: " + wasSuccess.toString() + "\nMessage: " + message + "\nData:" + data + "\n\n";
};
}
I've gotten something working but I'd still like to see other answers. This puts the event handler outside of the JS file and into the document, but the code itself is still inside the JS file. The organization of the code was my greatest concern so this is acceptable to me.
var oTest = new Test();
function Test()
{
var oDevice = new ActiveXObject("This.That");
this.CancelOperation = function()
{
try
{
oDevice.CancelOperation();
return "CancelOperation successful.";
}
catch (e)
{
return e.message;
}
};
this.WireEvents = function()
{
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'function oTest.oDevice::DeviceStatusUpdate(wasSuccess, message, data) { document.getElementById("outBox").value += "Success: " + wasSuccess.toString() + "\\nMessage: " + message + "\\nData:" + data + "\\n\\n"; }';
document.body.appendChild(script);
};
}

Is it possible to catch the exception generated by trying to connect to a bad url?

using node http package it doesn't seem possible to catch the exception caused by opening a bad URL. This is a problem, because it kills my cluster, which I'd like to guarantee will live forever
Here's the code: (uses fibers.promise)
function openConnection(dest, port, contentType, method, throwErrorOnBadStatus)
{
"use strict";
assert.ok(dest, "generalUtilities.openConnection: dest is null");
//dest = dest.replace('//','/');
console.log('opening connection: ' + dest + " contentType: " + contentType);
var prom = promise(),
errProm = promise(),
ar = [],
urlParts = url.parse(dest),
httpClient,
req,
got,
res;
//console.log('urlParts.port: ' + urlParts.port);
if (port) {
urlParts.port = port;
} else if (!urlParts.port) {
urlParts.port = 80;
}
if (contentType) {
urlParts.accept = contentType;
} else {
urlParts.contentType = 'text/html';
}
if (!urlParts.method) {
if (method) {
urlParts.method = method;
} else {
urlParts.method = 'GET';
}
}
try {
httpClient = http.createClient(urlParts.port, urlParts.hostname);
req = httpClient.request(urlParts.method, urlParts.path, urlParts);
//console.log('req: ' + req);
//if (req.connection) {
// req.connection.setTimeout(HTTP_REQUEST_TIMEOUT);
//}
//else {
// throw new Error ("No Connection Established!");
//}
req.end();
req.on('response', prom);
req.on('error', errProm);
got = promise.waitAny(prom, errProm);
if (got === errProm) {
//assert.ifError(errProm.get(), HTTP_REQUEST_TIMEOUT_MSG + dest);
throw new Error(HTTP_REQUEST_TIMEOUT_MSG + dest + ': ' + got.get());
}
res = prom.get();
ar.res = res;
ar.statusCode = res.statusCode;
if (ar.statusCode >= 300 && throwErrorOnBadStatus) {
assert.ifError("page not found!");
}
return ar;
}
catch (err) {
console.log(err);
}
}
and here's how I tested it
var promise = require('fibers-promise');
var gu = require("../src/utils/generalutilities.js");
var brokenSite = 'http://foo.bar.com:94//foo.js';
promise.start(function () {
try {
gu.openConnection(brokenSite, null, null, "GET", true);
}
catch (err) {
console.log('got: ' + err);
}
});
When I run this code I get:
Error: getaddrinfo ENOENT. It is never caught in the try catch
It works for me, when supplying an error handler for the request:
req.on('error', errorHandler);
I see that you also do that, but you set it after issuing
req.end();
Could you try issuing the end() after you attached the error handler?
As a side note, I really recommend request, as it handles issues like this with sensible defaults. It's really a breeze to work with.
Edit: Here is a simple example showing that attaching an error handler lets me handle ENOENT/ENOTFOUND errors:
var http = require('http');
var req = http.request({hostname: 'foo.example.com'}, function(err, res) {
if(err) return console.error(err);
console.log('got response!');
});
req.on('error', function(err) {
console.error('error!', err);
});
Another piece of valuable information: I'm not sure how it fits in with fibers, but in general, you should never throw in nodejs asynchronous code. It rarely works the way you want. Instead, use the standard practice of passing any error as the first parameter to the next callback, and handle the error where it makes sense (usually, high up in the call chain where you can do something sensible with it).
You can scrape the page for the error code.

Categories

Resources