Giter VIP home page Giter VIP logo

attempt's Introduction

@jill64/attempt

npm-version npm-license npm-download-month npm-min-size ci.yml

๐Ÿ’  Type safe error handling in one-line

Install

npm i @jill64/attempt

Usage

Include error objects in the return value with a syntax similar to Lodash.attempt.
Objects other than error instances are not captured.

import { attempt } from '@jill64/attempt'

// object | Error
const result = attempt(() => JSON.parse('Invalid JSON'))

Promise

Asynchronous functions can also be used.
Objects other than error instances are not captured.
Errors may be returned either synchronously or asynchronously.
See here for details.

import { attempt } from '@jill64/attempt'

// Promise<object> | Promise<Error> | Error
const result = attempt(async () => JSON.parse('Invalid JSON'))

Fallback Value

Returns the object specified as the second argument when an error is caught.
Objects other than error instances are not captured.

import { attempt } from '@jill64/attempt'

// object | null
const result = attempt(() => JSON.parse('Invalid JSON'), null)

Fallback Function

Executes the callback specified in the second argument when an error is caught.
The item filtered as an error instance is passed as the first argument of the callback.

import { attempt } from '@jill64/attempt'

// object | (string(error.message) | undefined)
const result = attempt(
  () => JSON.parse('Invalid JSON'),
  (error) => error?.message
)

Catch All Fallback Function

The raw thrown object is passed as the second argument to the callback.

import { attempt } from '@jill64/attempt'

// object | 'Syntax Error' | null
const result = attempt(
  () => JSON.parse('Invalid JSON'),
  (error, projectile) => {
    if (error instanceof SyntaxError) {
      return 'Syntax Error'
    }
    console.error('Unknown Object', projectile)
    return null
  }
)

Appendix

Why is an asynchronous function not returned as a Promise<Error> when specified?

Asynchronous function to Reject

// () => Promise<object>
const func = async () => {
  try {
    JSON.parse('Invalid JSON')
  } catch {
    throw new Error('Error')
  }
}

// Assign `null` by catch reject
const result = func().catch(() => null)

// `null`
return result

Asynchronous function that throws an error immediately (does not Reject)

// () => Promise<object>
const func = () => {
  try {
    const obj = JSON.parse('Invalid JSON')

    return new Promise(
      (resolve) => resolve(obj),
      (reject) => reject('Reject')
    )
  } catch {
    throw new Error('Error')
  }
}

// Error: Not Reject Error (Can't catch)
const result = func().catch(() => null)

return result

Although this is catchable in JavaScript syntax, it is actually thrown synchronously and cannot be caught.
Also, there is no way to check if a Promise is returned before the function is executed.
Therefore, the error return value of an asynchronous function is always Error | Promise<Error>.

License

MIT

attempt's People

Contributors

wraith-ci[bot] avatar renovate[bot] avatar jill64 avatar github-actions[bot] avatar dependabot[bot] avatar

Watchers

 avatar

attempt's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • jill64/.github main
npm
package.json
  • @jill64/eslint-config-ts 1.1.21
  • @jill64/prettier-config 1.0.0
  • typescript 5.4.5
  • vitest 1.6.0

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.