When should I use try catch instead of then catch? - javascript

The question is simple, but I haven't found the answer anywhere.
When should i use try catch? in the code below I use try catch to handle the return of a request:
async findUsers() {
this.loading = true;
try {
const [users, count] = await this.api.get('/users/list');
this.users = users;
this.totalPages = Math.ceil(parseInt(count) / 10);
}
catch (error) {
this.Messages.requestFailed(error);
}
finally {
this.loading = false;
}
}
Would it be a good practice to use then(...).catch(...)?

The difference is in how you're handing Promises.
If you're using await to handle the Promise then you wrap it in a try/catch. Think of await as a way to make asynchronous operations semantically similar to synchronous operations.
But if you're not using await and are instead handling the Promise by appending .then() to it then you'd append a .catch() to that chain to catch failures from within the asynchronous operation.
Because a try/catch isn't going to catch an exception that happens from within the asynchronous operation if that operation isn't awaited.

When you use promises(asynchronous operations) then you need to handle the exception in case of an error. So In this case you can use .then().catch(err) {}
When you have synchronous code, use try/catch for exception handling.

Related

How to catch an error thrown in an un-awaited async function inside try/ catch?

I'm hoping someone can suggest a better method for what I'm trying to achieve.
While performing a rather long and complicated webflow using puppeteer, occasionally an error will occur that disrupts the actions I'm trying to take on the page. There's nothing I can do about it in these situations other than return a useful error. However it doesn't happen often enough to explicitly wait and try to catch it after each step in my code.
The solution I have is:
async function runCode() {
try {
const page = browser.open(url)
listenForError(page)
await longWebFlow()
} catch (err) {
return err.message
}
}
async function listenForError(page) {
await page.waitForXPath(errorMessageXPath)
throw new Error('Error found!')
}
try {
await runCode()
} catch (err) {
console.log(err.message)
// should print('Error found')
}
Obviously, the unawaited listenForError call won't be caught in the try/catch, but I also cant await the call, or else I'll never get to the main part of the code.
The code works to short-circuit the process and return, since the error occurred, but how can I refactor this to catch the error message?
It seems like you want to wait until either the error is thrown or the longWebFlow() finishes - basically doing both concurrently. That's a perfect use case for promises with Promise.race:
async function runCode() {
const page = browser.open(url)
await Promise.race([
listenForError(page),
longWebFlow(),
]);
}
You could also use Promise.all if you made longWebFlow cancel the listenForError and fulfill the promise.
Either way, since you can properly await the promises now, the error also will be caught in the try/catch, as it should.
If you can't await the async operation then the only other "follow up" is with callbacks like .then() and .catch(). For example, you can catch the error here:
listenForError(page).catch(e => console.log(e));
This won't await the operation, it's just supplying a callback for whenever that operation fails at whatever point in the future.

Javascript - Change two function then/catch style into the async/await style

I'm try to understand how .then() function can get two arguments like this.
const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);
or
const promise2 = doSomething().then(successCallback, failureCallback);
but I want to convert two arguments .then() to async/await like this.
const result = await doSomething()
// execute successCallback if success.
// execute failureCallback if failure.
This is the website that I'm trying to learn.
Mozilla Firefox Developer : Using promise
Mozilla Firefox Developer : Promise Chaining
When you await a promise that resolves, you directly get its value:
const result = await doSomething();
When you await a promise that rejects, it throws an exception that you can either let propagate back to the caller of the current function (as a rejected promise since all async functions return a promise and async functions turn uncaught exceptions into a rejected promise) or you can catch it yourself locally with try/catch.
try {
const result = await doSomething();
} catch(e) {
console.log(e);
}
It is not recommended to map promises to callbacks. It's much better to just return the promise and let the caller deal with the promise directly either with .then() or await.
If you really needed to map await to successCallback and failureCallback, then you would do this:
try {
const result = await doSomething();
successCallback(result);
} catch(e) {
failureCallback(e);
}
But, at that point, you may as well just use .then() since it's less code:
doSomething().then(successCallback, failureCallback);
But, as I said earlier, you generally don't want to map promises into callbacks. It's more likely that you wrap older callback-based APIs into promises so you can use promises for all your control-flow and not mix/match models (which tends to seriously complicate good error handling when you mix models).
You can wrap the doSomething in a try catch method to capture the success and fail like this.
try {
const result = await doSomething()
} catch (err) {
console.log(err.message)
}
Use try...catch
try {
const result = await doSomething()
// success
successCallback();
}
catch (e) {
// error
failureCallback();

What is the proper way to handle errors in a promise?

I've been seeing a couple of different patterns for handling errors.
One is like:
let result;
try {
result = await forSomeResult(param);
} catch {
throw new Error();
}
And the other is like:
const result = await forSomeResult(param).catch(() => throw new Error());
I prefer the latter since it looks like a cleaner solution. But I've also heard talks that the first solution is better since there could be some race condition where the .catch doesn't execute before the next command is run.
I was wondering if someone had a technical answer about why one method is better than the other.
First of all, there's no reason to catch and throw or .catch() and throw unless you're going to do something else inside the catch handler or throw a different error. If you just want the same error thrown and aren't doing anything else, then you can just skip the catch or .catch() and let the original promise rejection go back to the caller.
Then, it is generally not recommended that you mix await with .catch() as the code is not as easy to follow. If you want to catch an exception from await, use try/catch around it. .catch() works, it's just not a preferred style if you're already awaiting the promise.
The one technical difference between these two styles:
async function someFunc()
let x = await fn().catch(err => {
console.log(err);
throw err;
});
// do something else with x
return something;
}
And, this:
async function someFunc()
let x;
try {
x = await fn();
} catch(err) {
console.log(err);
throw err;
}
// do something else with x
return something;
}
is if the function fn() you are calling throws synchronously (which it shouldn't by design, but could by accident), then the try/catch option will catch that synchronous exception too, but the .catch() will not. Because it's in an async function, the async function will catch the synchronous exception and turn it into a rejected promise for you automatically for the caller to see as a rejected promise, but it wouldn't get logged or handled in your .catch() handler.
One of the more beneficial cases for try/catch with await is when you have multiple await statements and you don't need to handle errors on any of them individually. Then, you can surround them with one try/catch and catch all the errors in one place.
async function someFunc(someFile) {
let fileHandle;
try {
// three await statements in a row, all using same try/catch
fileHandle = await fsp.open(someFile);
let data = await fsp.read(...);
// modify data
await fsp.write(...)
} catch(err) {
// just log and re-throw
console.log(err);
throw err;
} finally {
// close file handle
if (fileHandle) {
await fileHandle.close();
}
}
}
It depends.
Are you going to be calling multiple asynchronous functions that could error? You can wrap them all in a try/catch and perform common error handling without having to repeat yourself:
try {
result = await forSomeResult(param);
await forSomeOtherResult();
return await finalResult(result);
} catch { //catches all three at once!
throw new Error();
}
Do you only need to handle errors for this one, specific call? The .catch() pattern is fine. There is no race condition to worry about, await waits for the promise to resolve or reject, and this includes all success and failure callbacks attached to the promise. However, in your example, you're catching an error only to throw an empty one - in that case, it may be preferable to simply write this:
const result = await forSomeResult(param);
...and let the error propagate to the caller naturally.
I've seen a mixture of both styles used common enough that I think it's fine either way - they each have a particular strength.

Javascript Try Catch vs Catch chain

I recently ran into a Javascript problem catching errors and thus crashing when exception thrown.
funcReturnPromise().then().catch()
I had to change this to:
try {
funcReturnPromise().then()
} catch (e) {
...
}
Couldn't find a decent explanation for it, any JS wizards available to enlighten a JS peasant?
If funcReturnPromise() can throw synchronously (which functions that return promises should generally never do), then you do have to catch that synchronous exception with try/catch as you discovered when using regular .then().
This is one place where async functions can hep you. For example, if you declare funcReturnPromise as async, then the synchronous exception it throws will automatically become a rejected promise and the caller won't ever be exposed to a synchronous exception.
Or, if the caller (your code here) uses await, then you can catch both sycnhronous exceptions and rejected promises with the same try/catch.
So, for example, you could do this:
async function myFunc()
try {
let result = await funcReturnPromise();
console.log(result);
} catch (e) {
// this catches both a rejected promise AND
// a synchronously thrown exception
console.log(e);
}
}

Early returning inside an asynchronous function

Assume the scenario where you have to call an asynchronous function, but you are not really interested about success/failure situation of that function. In that case what are the pros and cons in following two patterns stated below with respect to call stack, callback queue and event loop
Pattern-1
async setSomething() {
try {
set(); // another async function
} catch (err) {
// log the error here
}
return true;
}
Pattern-2
async setSomething() {
try {
await set(); // another async function
} catch (err) {
// log the error here
}
return true;
}
Pattern 1 does not catch any errors that may occur during asynchronous operations in the set function - any errors will result in an unhandled Promise rejection, which should be avoided. Pattern 1 will only catch errors that occur during set's synchronous operations (such as, when setting up a fetch request), which are not likely to occur in most situations.
Example:
// open your browser's console to see the uncaught rejection
const set = () => new Promise((_, reject) => setTimeout(reject, 500));
async function setSomething() {
try {
set(); // another async function
} catch (err) {
console.log('err');
}
return true;
}
setSomething();
So, pattern 2 is likely preferable. If you don't care about the result of the asynchronous call, then don't await or call .then when you call setSomething().
Or, for something this simple, you might consider using Promise methods only, no async function needed:
const setSomething = () => set()
.catch((err) => {
// log the error here
});
This answer is a rather unconventional advice to the question than an actual answer to the examples posted by OP.
not really interested about success/failure situation of that function
If the above statement is the case, then it means, the return is not dependent on the result of the async invocation.
When you're not bothered about the return of the async invocation, it's better off to not use async/await or any type of promise at all. You could just invoke the function like any other function and process with the rest of the code.

Categories

Resources