What if JavaScript could chill a little bit with all the errors being thrown here and there?
function parse(raw) {
try {
return [ null, JSON.parse(raw) ]
} catch (err) {
return [ err, null ]
}
}
let [ err, ok ] = parse(...)| Nullable | try..catch and throw | Callback | Promise | chilled | |
|---|---|---|---|---|---|
| Sync | ✔️ | ✔️ | ✔️ | ||
| Async | ✔️ | ✔️ | ✔️ | ||
| Error Context | 😕 | ✔️ | ✔️ | ✔️ | |
| Composability | ✔️ | ✔️ | ✔️ |
Helps to capture the error close to the context when working with functions which throw exceptions.
const parse = chill(JSON.parse)
let [ err, ok ] = parse('{ "id": 1 }')
if (err) {
// Handle the error.
}
console.log(ok)Removes exception bubbling when using Async Await.
const url = 'https://jsonplaceholder.typicode.com/todos/1'
async function () {
let [ err, ok ] = await chill(
() => fetch(url).then(response => response.json())
)()
if (err) {
// Handle the error.
}
// Celebrate the success at async programming!
console.log(ok)
}()- Error handling and Go
- Result type from Elm
- Data.Either type from Haskell
- scopsy/await-to-js a JavaScript library exploring a similar concept
