Re-throwing exception on catch to upper level on async function - javascript

Throwing error to upper level in an async function
This
async create(body: NewDevice, firstTry = true): Promise<RepresentationalDevice> {
try {
return await this.dataAccess.getAccessToken()
} catch (error) {
throw error
}
}
VS this
async create(body: NewDevice, firstTry = true): Promise<RepresentationalDevice> {
return await this.dataAccess.getAccessToken()
}
I mean at the end on the upper level I must catch the error anyway and there is no modifications at all on the catch
Are these two approaches identical? Can I use the second approach without error handling issues?

This has nothing to do with async functions. Catching an error just to rethrow it is the same as not catching it in the first place. I.e.
try {
foo();
} catch(e) {
throw e;
}
and
foo();
are basically equivalent, except that the stack trace might be different (since in the first case the error is thrown at a different location).

Related

JavaScript equivalent for the "else" in try.. except.. else? [duplicate]

How can Javascript duplicate the four-part try-catch-else-finally execution model that other languages support?
A clear, brief summary is from the Python 2.5 what's new. In Javascript terms:
// XXX THIS EXAMPLE IS A SYNTAX ERROR
try {
// Protected-block
} catch(e) {
// Handler-block
} else {
// Else-block
} finally {
// Final-block
}
The code in Protected-block is executed. If the code throws an exception, Handler-block is executed; If no exception is thrown, Else-block is executed.
No matter what happened previously, Final-block is executed once the code block is complete and any thrown exceptions handled. Even if there’s an error in Handler-block or Else-block and a new exception is raised, the code in Final-block is still run.
Note that cutting Else-block and pasting at the end of Protected-block is wrong. If an error happens in Else-block, it must not be handled by Handler-block.
I know this is old, but here is a pure syntax solution, which I think is the proper way to go:
try {
// Protected-block
try {
// Else-block
} catch (e) {
// Else-handler-block
}
} catch(e) {
// Handler-block
} finally {
// Final-block
}
The code in Protected-block is executed. If the code throws an error, Handler-block is executed; If no error is thrown, Else-block is executed.
No matter what happened previously, Final-block is executed once the code block is complete and any thrown errors handled. Even if there’s an error in Handler-block or Else-block, the code in Final-block is still run.
If an error is thrown in the Else-block it is not handled by the Handler-block but instead by the Else-handler-block
And if you know that the Else-block will not throw:
try {
// Protected-block
// Else-block
} catch(e) {
// Handler-block
} finally {
// Final-block
}
Moral of the story, don't be afraid to indent ;)
Note: this works only if the Else-handler-block never throws.
Extending the idea of jhs a little, the whole concept could be put inside a function, to provide even more readability:
var try_catch_else_finally = function(protected_code, handler_code, else_code, finally_code) {
try {
var success = true;
try {
protected_code();
} catch(e) {
success = false;
handler_code({"exception_was": e});
}
if(success) {
else_code();
}
} finally {
finally_code();
}
};
Then we can use it like this (very similar to the python way):
try_catch_else_finally(function() {
// protected block
}, function() {
// handler block
}, function() {
// else block
}, function() {
// final-block
});
I know the question is old and answers has already given but I think that my answer is the simplest to get an "else" in javascripts try-catch-block.
var error = null;
try {
/*Protected-block*/
} catch ( caughtError ) {
error = caughtError; //necessary to make it available in finally-block
} finally {
if ( error ) {
/*Handler-block*/
/*e.g. console.log( 'error: ' + error.message );*/
} else {
/*Else-block*/
}
/*Final-block*/
}
Javascript does not have the syntax to support the no-exception scenario. The best workaround is nested try statements, similar to the "legacy" technique from PEP 341
// A pretty-good try/catch/else/finally implementation.
try {
var success = true;
try {
protected_code();
} catch(e) {
success = false;
handler_code({"exception_was": e});
}
if(success) {
else_code();
}
} finally {
this_always_runs();
}
Besides readability, the only problem is the success variable. If protected_code sets window.success = false, this will not work. A less readable but safer way uses a function namespace:
// A try/catch/else/finally implementation without changing variable bindings.
try {
(function() {
var success = true;
try {
protected_code();
} catch(e) {
success = false;
handler_code({"exception_was": e});
}
if(success) {
else_code();
}
})();
} finally {
this_always_runs();
}
Here's another solution if the problem is the common one of not wanting the error callback to be called if there is an uncaught error thrown by the first callback. ... i.e. conceptually you want ...
try {
//do block
cb(null, result);
} catch(err) {
// err report
cb(err)
}
But an error in the success cb causes the problem of cb getting called a second time. So instead I've started using
try {
//do block
try {
cb(null, result);
} catch(err) {
// report uncaught error
}
} catch(err) {
// err report
cb(err)
}
which is a variant on #cbarrick's solution.

Error handling in Q promise

I'm a bit confused understanding Q promise error handling. Let's say I have the following functions (for demonstration only):
function first() {
console.log('first');
var done = Q.defer();
done.resolve('first');
return done.promise;
}
function second() {
console.log('second');
var done = Q.defer();
done.resolve('second');
return done.promise;
}
function third() {
console.log('third');
var done = Q.defer();
done.resolve('third');
return done.promise;
}
function fourth() {
console.log('fourth');
var done = Q.defer();
done.resolve('fourth');
return done.promise;
}
function doWork() {
return first().then(function() {
return second();
}).then(function() {
return third()
}).then(function() {
return fourth();
});
}
doWork().catch(function(err) {
console.log(err);
});
Everything went fine.
Now that if in second, third or fourth function, I've got some errors (thrown by an async call for example), I could catch it gracefully.
For example, if in second, third or fourth function, I add:
throw new Error('async error');
The error is caught. Perfect!
But what makes me confused is that if the error is thrown in first function, the error is not caught and that breaks my execution.
Please someone tell me why or what I am doing wrong?
Thanks a lot!
Only exceptions in then callbacks are caught by promise implementations. If you throw in first, the exception will bubble and would only be caught by a try-catch statement.
That's exactly why asynchronous (promise-returning) functions should never throw. Instead, reject the promise you're returning (done.reject(…) or return Q.reject(…)). If you don't trust your function, you can use Promise.resolve().then(first).… to start your chain.
Wrap the logic that can break in a try block and reject the promise with the error in the catch block.
var def = q.defer();
try {
// sync or async logic that can break
}
catch (ex) {
q.reject(ex);
}
return def;

Catching Errors in JavaScript Promises with a First Level try ... catch

So, I want my first level catch to be the one that handles the error. Is there anyway to propagate my error up to that first catch?
Reference code, not working (yet):
Promise = require('./framework/libraries/bluebird.js');
function promise() {
var promise = new Promise(function(resolve, reject) {
throw('Oh no!');
});
promise.catch(function(error) {
throw(error);
});
}
try {
promise();
}
// I WANT THIS CATCH TO CATCH THE ERROR THROWN IN THE PROMISE
catch(error) {
console.log('Caught!', error);
}
You cannot use try-catch statements to handle exceptions thrown asynchronously, as the function has "returned" before any exception is thrown. You should instead use the promise.then and promise.catch methods, which represent the asynchronous equivalent of the try-catch statement. (Or use the async/await syntax noted in #Edo's answer.)
What you need to do is to return the promise, then chain another .catch to it:
function promise() {
var promise = new Promise(function(resolve, reject) {
throw('Oh no!');
});
return promise.catch(function(error) {
throw(error);
});
}
promise().catch(function(error) {
console.log('Caught!', error);
});
Promises are chainable, so if a promise rethrows an error, it will be delegated down to the next .catch.
By the way, you don't need to use parentheses around throw statements (throw a is the same as throw(a)).
With the new async/await syntax you can achieve this. Please note that at the moment of writing this is not supported by all browsers, you probably need to transpile your code with babel (or something similar).
// Because of the "async" keyword here, calling getSomeValue()
// will return a promise.
async function getSomeValue() {
if (somethingIsNotOk) {
throw new Error('uh oh');
} else {
return 'Yay!';
}
}
async function() {
try {
// "await" will wait for the promise to resolve or reject
// if it rejects, an error will be thrown, which you can
// catch with a regular try/catch block
const someValue = await getSomeValue();
doSomethingWith(someValue);
} catch (error) {
console.error(error);
}
}
No! That's completely impossible, as promises are inherently asynchronous. The try-catch clause will have finished execution when the exception is thrown (and time travel still will not have been invented).
Instead, return promises from all your functions, and hook an error handler on them.
I often find the need to ensure a Promise is returned and almost as often needing to handle a local error and then optionally rethrow it.
function doSomeWork() {
return Promise.try(function() {
return request.get(url).then(function(response) {
// ... do some specific work
});
}).catch(function(err) {
console.log("Some specific work failed", err);
throw err; // IMPORTANT! throw unless you intend to suppress the error
});
}
The benefit of this technique (Promise.try/catch) is that you start/ensure a Promise chain without the resolve/reject requirement which can easily be missed and create a debugging nightmare.
To expand on edo's answer, if you want to catch the errors of an async function that you don't want to wait for. You can add an await statement at the end of your function.
(async function() {
try {
const asyncResult = someAsyncAction();
// "await" will wait for the promise to resolve or reject
// if it rejects, an error will be thrown, which you can
// catch with a regular try/catch block
const someValue = await getSomeValue();
doSomethingWith(someValue);
await asyncResult;
} catch (error) {
console.error(error);
}
})();
If someAsyncAction fails the catch statement will handle it.

catch exception in its initializer object

I have an Ajax object which is used in some other objects to load 'Json' files.
I need to catch the 404 'Not found' thrown exception in the initializer object, but I couldn't do this it always gives me:
Uncaught Exception : *********
here a piece of code:
_ajax_params.xmlhttp.onreadystatechange = function() {
if (_ajax_params.xmlhttp.readyState==4 && _ajax_params.xmlhttp.status==200) {
_ajax_params.response = _ajax_params.xmlhttp.responseText;
if (typeof afterClosure == 'function') {
afterClosure(_ajax_params.response);
}
COMMON.always(_ajax_params.response);
} else if (_ajax_params.xmlhttp.status== 404) {
throw 'File not found';
}
};
In the initializer object:
try {
Base.include.json(url, 1);
} catch (e) {
console.error(e);
Base.include.json(url,2);
}
I tried to re-throw exception, but I got the same.
You may have defined the callback within a try..catch block, but the function is executed outside of said block (ie. when the event is fired). This means that exceptions that happen in the callback will not be caught by the outside block.
Here is a demonstration of the difference in action.
Consider calling Base.include.json(url,2) in place of throw 'File not found';
Additionally, you shouldn't really check status unless you already know that readyState is 4, but that's a minor thing.

Javascript try...catch...else...finally like Python, Java, Ruby, etc

How can Javascript duplicate the four-part try-catch-else-finally execution model that other languages support?
A clear, brief summary is from the Python 2.5 what's new. In Javascript terms:
// XXX THIS EXAMPLE IS A SYNTAX ERROR
try {
// Protected-block
} catch(e) {
// Handler-block
} else {
// Else-block
} finally {
// Final-block
}
The code in Protected-block is executed. If the code throws an exception, Handler-block is executed; If no exception is thrown, Else-block is executed.
No matter what happened previously, Final-block is executed once the code block is complete and any thrown exceptions handled. Even if there’s an error in Handler-block or Else-block and a new exception is raised, the code in Final-block is still run.
Note that cutting Else-block and pasting at the end of Protected-block is wrong. If an error happens in Else-block, it must not be handled by Handler-block.
I know this is old, but here is a pure syntax solution, which I think is the proper way to go:
try {
// Protected-block
try {
// Else-block
} catch (e) {
// Else-handler-block
}
} catch(e) {
// Handler-block
} finally {
// Final-block
}
The code in Protected-block is executed. If the code throws an error, Handler-block is executed; If no error is thrown, Else-block is executed.
No matter what happened previously, Final-block is executed once the code block is complete and any thrown errors handled. Even if there’s an error in Handler-block or Else-block, the code in Final-block is still run.
If an error is thrown in the Else-block it is not handled by the Handler-block but instead by the Else-handler-block
And if you know that the Else-block will not throw:
try {
// Protected-block
// Else-block
} catch(e) {
// Handler-block
} finally {
// Final-block
}
Moral of the story, don't be afraid to indent ;)
Note: this works only if the Else-handler-block never throws.
Extending the idea of jhs a little, the whole concept could be put inside a function, to provide even more readability:
var try_catch_else_finally = function(protected_code, handler_code, else_code, finally_code) {
try {
var success = true;
try {
protected_code();
} catch(e) {
success = false;
handler_code({"exception_was": e});
}
if(success) {
else_code();
}
} finally {
finally_code();
}
};
Then we can use it like this (very similar to the python way):
try_catch_else_finally(function() {
// protected block
}, function() {
// handler block
}, function() {
// else block
}, function() {
// final-block
});
I know the question is old and answers has already given but I think that my answer is the simplest to get an "else" in javascripts try-catch-block.
var error = null;
try {
/*Protected-block*/
} catch ( caughtError ) {
error = caughtError; //necessary to make it available in finally-block
} finally {
if ( error ) {
/*Handler-block*/
/*e.g. console.log( 'error: ' + error.message );*/
} else {
/*Else-block*/
}
/*Final-block*/
}
Javascript does not have the syntax to support the no-exception scenario. The best workaround is nested try statements, similar to the "legacy" technique from PEP 341
// A pretty-good try/catch/else/finally implementation.
try {
var success = true;
try {
protected_code();
} catch(e) {
success = false;
handler_code({"exception_was": e});
}
if(success) {
else_code();
}
} finally {
this_always_runs();
}
Besides readability, the only problem is the success variable. If protected_code sets window.success = false, this will not work. A less readable but safer way uses a function namespace:
// A try/catch/else/finally implementation without changing variable bindings.
try {
(function() {
var success = true;
try {
protected_code();
} catch(e) {
success = false;
handler_code({"exception_was": e});
}
if(success) {
else_code();
}
})();
} finally {
this_always_runs();
}
Here's another solution if the problem is the common one of not wanting the error callback to be called if there is an uncaught error thrown by the first callback. ... i.e. conceptually you want ...
try {
//do block
cb(null, result);
} catch(err) {
// err report
cb(err)
}
But an error in the success cb causes the problem of cb getting called a second time. So instead I've started using
try {
//do block
try {
cb(null, result);
} catch(err) {
// report uncaught error
}
} catch(err) {
// err report
cb(err)
}
which is a variant on #cbarrick's solution.

Categories

Resources