项目作者: halfzebra

项目描述 :
:ok_hand: Resilient error handling pattern for JavaScript
高级语言: JavaScript
项目地址: git://github.com/halfzebra/chilled-js.git
创建时间: 2019-05-19T20:48:37Z
项目社区:https://github.com/halfzebra/chilled-js

开源协议:

下载


chilled-js

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

Build Status

TL;DR

  1. function parse(raw) {
  2. try {
  3. return [ null, JSON.parse(raw) ]
  4. } catch (err) {
  5. return [ err, null ]
  6. }
  7. }
  8. let [ err, ok ] = parse(...)

Comparing to other kinds of error handling

Nullable try..catch and throw Callback Promise chilled
Sync :heavy_check_mark: :heavy_check_mark: :heavy_check_mark:
Async :heavy_check_mark: :heavy_check_mark: :heavy_check_mark:
Error Context :confused: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark:
Composability :heavy_check_mark: :heavy_check_mark: :heavy_check_mark:

Dr. Freeze saying "Everybody Chill!"

Usage

Sync

Helps to capture the error close to the context when working with functions which throw exceptions.

  1. const parse = chill(JSON.parse)
  2. let [ err, ok ] = parse('{ "id": 1 }')
  3. if (err) {
  4. // Handle the error.
  5. }
  6. console.log(ok)

Async

Removes exception bubbling when using Async Await.

  1. const url = 'https://jsonplaceholder.typicode.com/todos/1'
  2. async function () {
  3. let [ err, ok ] = await chill(
  4. () => fetch(url).then(response => response.json())
  5. )()
  6. if (err) {
  7. // Handle the error.
  8. }
  9. // Celebrate the success at async programming!
  10. console.log(ok)
  11. }()

Inspiration