DEV Community

Discussion on: Error Handling in JavaScript (Golang Style)

Collapse
 
drumstickz64 profile image
Drumstickz64 • Edited

You can actually turn this into a utility function, like so:

async function goCatch(promise) {
    try {
        const result = await promise
        return [result, null]
    } catch (err) {
        return [null, err]
    }
}
Enter fullscreen mode Exit fullscreen mode

You could also use an object like Brendan said.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

I would wrap it in a higher order function though, something that takes an async function and returns a new async function with the added catch logic

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

Something like this, I guess:

const safe = fn => (*args) => fn(*args)
   .then(res => [res, null])
   .catch(err => [null, err])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bibekkakati profile image
Bibek

Yeah. That can be way of implementing it.

Collapse
 
bibekkakati profile image
Bibek • Edited

Yeah. Utility function can be very helpful.