Sending handled (not just unhandled) Javascript errors to server - javascript

I'm trying to send ALL my Javascript exceptions, handled as well as unhandled ones, to server for logging. I've gone through window.onerror documentation and also this post that throws light on this issue, but they work best for unhandled exceptions only.
window.onerror does not fire if the exception is already handled in a catch() block.
One 'painful' way would be to attach my logToServer() function manually to every catch() block in my code (and it works too), but I'm hoping for a better solution.
I've set up a little snippet below.
var logToServer = function logToServer() {
console.info('logToServer() called');
};
window.onerror = function(z, x, c, v, b) {
console.info(z);
console.info(x);
console.info(c);
console.info(v);
console.info(b);
// call a function to send to server
logToServer();
};
window.addEventListener('error', function(z, x, c, v, b) {
console.info(z);
// call a function to send to server
logToServer();
});
// test w/o catch-block
//console.info(err); // calls logToServer()
// test w/ catch-block
try {
console.info(asd); // does not call logToServer()
} catch (err) {
console.error(err);
};
Enable logs in console.

window.onerror fires only when an exception is unhandled. If you catch any exception, this event wont fire. You will have to do it explicitly in all try--catch blocks. In catch block you will have to throw your exception. The syntax is simple:
try{
//Your try logic
}
catch(ex){
// Your catch logic comes here
throw ex; //This will throw exception and window.onerror will be fired.
}

Related

Where to CATCH an EXCEPTION thrown within an EVAL

The following script enables you to run a piece of javascript code. Errors are being catched by the try / catch block.
try {
var result = eval(script);
} catch (e) {
// do something meaningful
}
However, if the variable script contains for instance an AJAX call, and this ajax call throws an exception (e.g. in the success function), this exception will NOT be catched by this try / catch block...
// execute an AJAX request
var script = '$.ajax(url:"/somewhere", success: function(){throw new MyException('testexception')})';
try {
var result = eval(script);
} catch (e) {
// will not be triggered...
}
Question: how can I catch the exception thrown within the ajax request?
I hope you are aware of the dangers of using eval, and if not there are plenty of good articles out there that explain why it is not a good idea.
That being said, the issue is that the success callback is being called after the catch block. You'll need to either add the try/catch block within the success callback, or you'll need to handle the error from a more global perspective. One idea I can think of to do this is using the window.onerror event. I have an example below that shows something similar to your problem, and one that shows you can catch errors thrown in eval.
(function() {
'use strict';
window.addEventListener('error', e => console.log(`window.onerror: ${e.message}`));
let script = `setTimeout(function() {
throw new Error('Whoops!');
}, 0);`;
eval(script);
script = `throw new Error('Whoops!');`;
try {
eval(script);
} catch (e) {
console.log(e.message);
}
})();

Chai-As-Promised: Handle errors when promise throws error

I have the following code I need to test:
function A(param){
// Process param
return B(param)
.catch(function(err){
//Process err
throw new customError(err); // throw a custom Error
})
.then(function(response){
// Handle response and return
return {status: 'Success'}
})
}
To test it, I use the following snippet:
return expect(A(param))
.to.eventually.have.property('status', 'Success');
This works fine when the code doesn't break in function A or B, but when it does, the test case fails, and the grunt-mocha fails to exit, which I presume is due to the fact that it still waiting for A to resolve.
If I add a return statement instead of throw in catch block, grunt-mocha exits fine. Is there a better way to test such cases?
Catch is meant to catch and correct any errors, not re-throw them. So returning the error or a rejected promise is the correct way to handle this.

Disable error handling for mocha.js

Does anyone know if there a way to disable error handling by Mocha?
I'd really like to let the exception bubble up and be handled by the browser during debugging.
Update:
The context is this.
- Some code throw's an unexpected error.
- I would like to disable "try/catch" (something like jasmine's tests do) and be thrown into the debugger in chrome.
This way I can inspect the current state of the application at that moment.
It sounds like there isn't something built in, and I will need to manually do this each time I get some odd error in a test. Maybe by wrapping my code with
try {
somethingThatBreaks();
} catch(e) {
debugger;
}
Mocha installs its own onerror handler to trap exceptions that may occur in asynchronous code. You can disable it with:
window.onerror = undefined;
This is dangerous. You should do this only when you must absolutely do so. If you make this a routine thing, Mocha will completely miss errors that happen in asynchronous code.
If what you want to do is let exceptions in synchronous code bubble up, I'm not seeing what this would accomplish. If you want to inspect the exception before Mocha touches it, a try...catch block wrapping your test will do this.
Mocha's error handling is contained in the following code:
if (this.async) {
try {
this.fn.call(ctx, function(err){
if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
done();
});
} catch (err) {
done(err);
}
return;
}
// sync
try {
if (!this.pending) this.fn.call(ctx);
this.duration = new Date - start;
fn();
} catch (err) {
fn(err);
}
You could possibly throw the error with the catch (or remove the try..catch entirely) however it would most likely break the test suite if a test fails.
mocha.options.allowUncaught=true
But in this case, the rest of the tests will break if the error is not caught within mocha. Disabling try{} catch(){} in mocha will only be useful when debugging.
To create a test, I suggest using the construction
(for browser)
try{
throw new Error()
} catch (e){
// Let's say it's called in a yor error listeners.
e.handler=()=>{
done(e)
}
let event= new ErrorEvent('error',{error:e})
window.dispatchEvent(event);
}

Strategies for handling exceptions between ticks (or, stacks) in Node.js? [duplicate]

This question already has answers here:
Is it possible to catch exceptions thrown in a JavaScript async callback?
(7 answers)
Closed 9 years ago.
I've got the following:
var http = require('http');
server = http.createServer(function(request, response) {
try {
// Register a callback: this happens on a new stack on some later tick
request.on('end', function() {
throw new Error; // Not caught
})
throw new Error; // Caught below
}
catch (e) {
// Handle logic
}
}
Now, the first Error gets caught in the try...catch, but the second Error does not appear to be getting caught.
A couple questions:
Does the second Error not get caught because it occurs on a different stack? If so, am I to understand that try...catch behavior is not lexically bound, but depends instead on the current stack? Am I interpreting this correctly?
Are there any well-explored patterns to handle this type of problem?
You could also use a simple EventEmitter to handle an error in a case like this.
var http = require('http');
var EventEmitter = require("events").EventEmitter;
server = http.createServer(function(request, response) {
var errorHandler = new EventEmitter;
// Register a callback: this happens on a new stack on some later tick
request.on('end', function() {
if(someCondition) {
errorHandler.emit("error", new Error("Something went terribly wrong"));
}
});
errorHandler.on("error", function(err) {
// tell me what the trouble is....
});
});
The second error is never thrown, nor caught. You throw an error before you add your anonymous function as a handler for request's end event.
Even if you had, it isn't going to be caught, as it is indeed on a different stack. You must raise an error event if you want to work this way, or simply pass error as the first callback parameter to any callback function. (These are both common conventions, not mandates.)
catch catches Errors that are thrown while executing the content of its try block. Your 'end' handler is created and assigned inside the try block, but it obviously doesn't execute there. It executes when request fires its end event, and the try block will be long forgotten by then.
You'll generally want to catch errors within your event handler and not let them percolate up through the stack. You'll never/rarely want to throw them.
As a last resort, you can register an handler for 'uncaughtException' on process, which will catch all exceptions that aren't caught elsewhere. But that's rarely the right solution. http://nodejs.org/api/process.html#process_event_uncaughtexception

Is try {} without catch {} possible in JavaScript?

I have a number of functions which either return something or throw an error. In a main function, I call each of these, and would like to return the value returned by each function, or go on to the second function if the first functions throws an error.
So basically what I currently have is:
function testAll() {
try { return func1(); } catch(e) {}
try { return func2(); } catch(e) {} // If func1 throws error, try func2
try { return func3(); } catch(e) {} // If func2 throws error, try func3
}
But actually I'd like to only try to return it (i.e. if it doesn't throw an error). I do not need the catch block. However, code like try {} fails because it is missing an (unused) catch {} block.
I put an example on jsFiddle.
So, is there any way to have those catch blocks removed whilst achieving the same effect?
A try without a catch clause sends its error to the next higher catch, or the window, if there is no catch defined within that try.
If you do not have a catch, a try expression requires a finally clause.
try {
// whatever;
} finally {
// always runs
}
It's possible to have an empty catch block, without an error variable, starting with ES2019. This is called optional catch binding and was implemented in V8 v6.6, released in June 2018. The feature has been available since Node 10, Chrome 66, Firefox 58, Opera 53 and Safari 11.1.
The syntax is shown below:
try {
throw new Error("This won't show anything");
} catch { };
You still need a catch block, but it can be empty and you don't need to pass any variable. If you don't want a catch block at all, you can use the try/finally, but note that it won't swallow errors as an empty catch does.
try {
throw new Error("This WILL get logged");
} finally {
console.log("This syntax does not swallow errors");
}
Nope, catch (or finally) is try's friend and always there as part of try/catch.
However, it is perfectly valid to have them empty, like in your example.
In the comments in your example code (If func1 throws error, try func2), it would seem that what you really want to do is call the next function inside of the catch block of the previous.
I wouldn't recommend try-finally without the catch, because if both the try block and finally block throw errors, the error thrown in the finally clause gets bubbled up and the try block's error is ignored, in my own test:
try {
console.log('about to error, guys!');
throw new Error('eat me!');
} finally {
console.log ('finally, who cares');
throw new Error('finally error');
}
Result:
> about to error, guys!
> finally, who cares
> .../error.js:9
> throw new Error('finally error');
> ^
>
> Error: finally error
No, it is not possible to have try block without catch (or finally). As a workaround, I believe you might want to define a helper function such as this:
function tryIt(fn, ...args) {
try {
return fn(...args);
} catch {}
}
and use it like:
tryIt(function1, /* args if any */);
tryIt(function2, /* args if any */);
I've decide to look at the problem presented from a different angle.
I've been able to determine a way to to allow closely for the code pattern requested while in part addressing the un-handled error object listed by another commenter.
code can be seen # http://jsfiddle.net/Abyssoft/RC7Nw/4/
try:catch is placed within a for loop allowing graceful fall through. while being able to iterate through all the functions needed. when explicit error handling is needed additional function array is used. in the even of error and functional array with error handlers element is not a function, error is dumped to console.
Per requirements of stackoverflow here is the code inline [edited to make JSLint compliant (remove leading spaces to confirm), improve readability]
function func1() {"use strict"; throw "I don't return anything"; }
function func2() {"use strict"; return 123; }
function func3() {"use strict"; throw "I don't return anything"; }
// ctr = Code to Run <array>, values = values <array>,
// eh = error code can be blank.
// ctr and params should match 1 <-> 1
// Data validation not done here simple POC
function testAll(ctr, values, eh) {
"use strict";
var cb; // cb = code block counter
for (cb in ctr) {
if (ctr.hasOwnProperty(cb)) {
try {
return ctr[cb](values[cb]);
} catch (e) {
if (typeof eh[cb] === "function") {
eh[cb](e);
} else {
//error intentionally/accidentially ignored
console.log(e);
}
}
}
}
return false;
}
window.alert(testAll([func1, func2, func3], [], []));
​
If you only want functions 2 and 3 to fire if an error occurs why are you not putting them in the catch block?
function testAll() {
try {
return func1();
} catch(e) {
try {
return func2();
} catch(e) {
try {
return func3();
} catch(e) {
// LOG EVERYTHING FAILED
}
}
}
}
...is there any way to have those catch blocks removed whilst achieving the same effect? As it would seem, no; Javascript requires a try block be followed by either a catch or a finally block.
Having said that, there is a way to use those catch blocks to achieve the effect you want.
// If func1 throws error, try func2 The if throws error condition, is what the catch block is for.
Why remove them when their use is exactly what you are after?
try { return func1(); }
catch {
// if func1 throws error
try { return func2(); }
catch {
// if func2 throws error
try { return func3(); }
catch {
// if func3 throws error
}
}
}
I completely understand why you might not need a catch block, and would find it cleaner to be able to omit it entirely. But I don't think this is one of those situations.
They go together in every language that I know that has them (JavaScript, Java, C#, C++). Don't do it.
Since ES2019 you can easily use try {} without catch {}:
try {
parseResult = JSON.parse(potentiallyMalformedJSON);
} catch (unused) {}
For more info please reffer to Michael Ficcara's proposal
try & catch are like 2 side of one coin. so not possible without try.
No. You have to keep them.
This actually makes sense since errors shouldn't be silently ignored at all.

Categories