express-async-error-catcher
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

express-async-error-catcher

Catch errors in async request handlers and forward them to your error handler

Install

npm i express-async-error-catcher

Features

  • Forward errors from rejected promises to your error handler
  • Forwards the router generics from its .get, .put, .post, .delete to your request handler, if you'r using typescript

Example

import express, { Request, Response, NextFunction } from "express"
import { asyncErrorCatcher } from "express-async-error-catcher"

const app = express()

app.get("/safe", asyncErrorCatcher(async (req, res) => {
  await new Promise((res, rej) => {
    setTimeout(() => rej("rejected"), 2000) // Is caught by 'errorHandler' after 2s
  })
  // ...
}))
app.get("/unsafe", async (req, res) => {
  await new Promise((res, rej) => {
    setTimeout(() => rej("rejected"), 2000) // Is NOT caught by 'errorHandler' Terminates express with 'UnhandledPromiseRejection'
  })
  // ...
})

const errorHandler = (error: Error, request: Request, response: Response, next: NextFunction) => {
  console.log("caught error", error)
  // ...
}

app.use(errorHandler)
app.listen(3000)

Package Sidebar

Install

npm i express-async-error-catcher

Weekly Downloads

1

Version

1.0.3

License

MIT

Unpacked Size

4.53 kB

Total Files

6

Last publish

Collaborators

  • mroffersen