@seamapi/nextjs-exception-middleware
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

nextjs-exception-middleware

This middleware allows you to throw exceptions in your route handlers that are caught and returned as JSON.

For example,

// Inside a route handler
if (bad_soups.includes(soup_param)) {
  throw new BadRequestException({
    type: "cant_make_soup",
    message: "Soup was too difficult, please specify a different soup",
    data: { soup_param }
  })
}

will be returned as

{
  "error": {
    "type": "cant_make_soup",
    "message": "Soup was too difficult, please specify a different soup",
    "data": {
      "soup_param": "tomato"
    }
  }
}

with a status code of 400.

Installation

yarn add @seamapi/nextjs-exception-middleware or npm install @seamapi/nextjs-exception-middleware -s

Usage

Wrap your API handlers like so:

import { withExceptionHandling } from "@seamapi/nextjs-exception-middleware"

export default withExceptionHandling({
  // all parameters are optional
  addOkStatus: false // add top-level "ok" status key to JSON responses
  okStatusOptions: {
    addIf: (req) => req.method === "GET" // only add "ok" status key if request is GET
  },
  exceptionHandlingOptions: {
    shouldIncludeErrorContext: (req) => req.method === "GET" // only include error stack if request is GET
    getAdditionalErrorContext: (req) => ({
      // add any additional context to returned errors
      "request_id": req.requestId
    })
  }
})(async (req, res) => {
  // ...
})

Readme

Keywords

none

Package Sidebar

Install

npm i @seamapi/nextjs-exception-middleware

Weekly Downloads

0

Version

1.1.1

License

MIT

Unpacked Size

19.9 kB

Total Files

5

Last publish

Collaborators

  • codetheweb
  • razorx
  • seambot
  • dawnho
  • sybohy