Skip to content

👌 Resilient error handling pattern for JavaScript

Notifications You must be signed in to change notification settings

halfzebra/chilled-js

Repository files navigation

chilled-js

What if JavaScript could chill a little bit with all the errors being thrown here and there?

Build Status

TL;DR

function parse(raw) {
  try {
    return [ null, JSON.parse(raw) ]
  } catch (err) {
    return [ err, null ]
  }
}

let [ err, ok ] = parse(...)

Comparing to other kinds of error handling

Nullable try..catch and throw Callback Promise chilled
Sync ✔️ ✔️ ✔️
Async ✔️ ✔️ ✔️
Error Context 😕 ✔️ ✔️ ✔️
Composability ✔️ ✔️ ✔️

Dr. Freeze saying "Everybody Chill!"

Usage

Sync

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)

Async

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)
}()

Inspiration

About

👌 Resilient error handling pattern for JavaScript

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published