@seamapi/nextjs-exception-middleware
v1.1.1
Published
This middleware allows you to throw exceptions in your route handlers that are caught and returned as JSON.
Downloads
3
Keywords
Readme
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) => {
// ...
})