For exceptions, try...catch
is the way to go in JS. By introducing async/await
, we can use the try...catch
statement for asynchronous code as well:
let greeting
try {
greeting = await helloAsync("World")
}
catch(err) {
greeting = "Hello World"
}
console.log(greeting)
async function helloAsync(name: string): string {
if (name === "") {
throw new RangeError("`name` can't be empty")
}
return `Hello ${name}`
}
The code is not the most elegant. When you have more "try...catches" in code, it becomes less readable. It's easier to assume that code is "perfect" and skip error handling. As a result, many developers are scared of using throw new Error()
.
After spending some time with golang
, I'm amazed how well the language is designed in this matter. Inspired by golang
, I have created a simple utility called go
which drastically simplify the error handling:
function go<T>(promise: T) {
return Promise.resolve(promise)
.then(result => [null, result] as const)
.catch(err => [err, null] as const)
}
Here the example from the begging:
let [err, greeting] = await go(helloAsync("Andrii"))
if (err) {
greeting = "Hello World"
}
console.log(greeting)
Take care, and watch for the errors!
Top comments (0)