await...catch

The current async/await syntactic sugar, which is supposed to simplify code and make it more readable, fails in regard to error handling. You either need to use noisy try...catch blocks or ugly .catch calls like below:

try {
  await promiser();
} catch (error) {
  console.warn(error);
  doFallback();
}

// or

await promiser()
.catch(error => {
  console.warn(error);
  doFallback();
});

Idea: A minimalistic await...catch block syntax:

await promiser();
catch (error) {
  console.warn(error);
  doFallback();
}

// or

await promiser() catch (error) {
  console.warn(error);
  doFallback();
}
1 Like

Hi,

I agree that handling errors with try/catch is clumsy. But this is completely orthogonal to async and promises. The async/await sugar allows you to write asynchronous code without callback hell, but it is not supposed to patch the clumsy try/catch pattern.

If you control your API, you can still return instead of throwing (in sync code), and you can still resolve instead of rejecting (in promises). Example:

JSON.$parse = function (x) {
    try { return JSON.parse(x) } catch(e) { }
}
// or:
JSON.$asyncParse = async function (x) {
    // some async JSON parser that produces
    // undefined when there is an error.
}


var result = JSON.$parse(someRandomString)
// or:
var result = await JSON.$asyncParse(someRandomString)

if (result === undefined) {
  console.warn("Something got wrong with your random string");
  doFallback();
}

If it deemed worth to make the try/catch pattern more palatable, the solution should work both for sync and async code.

Related: https://github.com/isiahmeadows/proposal-try-expression