Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

async-fn-catch

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

async-fn-catch

async function error catching can be a bit tricky

  • 0.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

Async Fn Catch

Async function error handling can be tricky. As the author of a plugin I don't want to create nearly impossible errors to catch. I like them to be exposed to the user in a simple interface.

This is a solution I have found to be useful.

Install

npm install async-fn-catch --save
# or
yarn add async-fn-catch

Usage

// import function
const asyncCatch = require('async-fn-catch')
// or
import asyncCatch from 'async-fn-catch'

This first example shows how you wrap a function with async-fn-catch to make the error super easy to catch. You could do the same by adding a .catch to the foo() call. Which is essentially what this lib is doing.

const errorHandler = err => console.log(err) // just log error

const foo = asyncCatch(
  async function fooAsync () {
    await bar() // error happens in here
  },
  errorHandler
)

async function bar () {
  ... // do complex stuff
  throw new Error('qux')
}

foo() // logs -> Error "qux"

This next example shows how error handling with async can get a bit trickier when dealing with methods in a class.

class Foo extends EventEmitter {
  constructor () {
    super()
    this.bar = asyncCatch(
      this.bar.bind(this),
      this.onError.bind(this)
    )
  }
  onError (err) { this.emit('error', err)}
  async bar () { await this.baz() }
  async baz () { throw new Error('qux') }
}

const foo = new Foo()
foo.on('error', (err) => console.log(err))
foo.bar() // logs -> Error "qux"

FAQs

Package last updated on 23 Oct 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc