middy-middleware-json-error-handler
Version:
A middy JSON error handler middleware.
61 lines (47 loc) • 3.46 kB
Markdown
//badge.fury.io/js/middy-middleware-json-error-handler.svg)](https://npmjs.org/package/middy-middleware-json-error-handler)
[](https://npmjs.org/package/middy-middleware-json-error-handler)
[](https://github.com/dbartholomae/middy-middleware-json-error-handler/issues)
[](https://app.fossa.io/projects/git%2Bgithub.com%2Fdbartholomae%2Fmiddy-middleware-json-error-handler?ref=badge_shield)
[](https://github.com/visionmedia/debug#readme)
[](https://github.com/dbartholomae/middy-middleware-json-error-handler/actions?query=workflow%3A"Build+and+deploy")
[](https://codecov.io/gh/dbartholomae/middy-middleware-json-error-handler)
[](https://github.com/semantic-release/semantic-release#badge)
A [middy](https://github.com/middyjs/middy) middleware that returns errors as http errors, compatible with [http-errors](https://www.npmjs.com/package/http-errors).
Download node at [nodejs.org](http://nodejs.org) and install it, if you haven't already.
```sh
npm install middy-middleware-json-error-handler --save
```
There is [additional documentation](https://dbartholomae.github.com/middy-middleware-json-error-handler).
```typescript
import middy from '@middy/core'
import JSONErrorHandlerMiddleware from 'middy-middleware-json-error-handler'
import createHttpError from 'http-errors'
import { APIGatewayEvent } from 'aws-lambda'
// This is your AWS handler
async function helloWorld (event: APIGatewayEvent) {
if (event.queryStringParameters?.search == null) {
// If you throw an error with status code, the error will be returned as stringified JSON.
// Only the stack will be omitted.
throw createHttpError(400, 'Query has to include a search')
}
if (event.queryStringParameters?.search === 'error') {
// If you throw an error with status code greater than 500 and specify in options that the error
// must be exposed, then the error will be returned as stringified JSON
throw createHttpError(500, 'Something went wrong', { expose: true })
}
// If you throw an error with no status code, only a generic message will be shown to the user
// instead of the full error
throw new Error('Search is not implemented yet')
}
// Specify which are the error properties to omit in response (by default, only the stack is omitted)
const options = {
errorPropertiesToOmit: ['name', 'statusCode', 'stack']
}
// Let's "middyfy" our handler, then we will be able to attach middlewares to it (options parameter is optional)
export const handler = middy(helloWorld)
.use(JSONErrorHandlerMiddleware(options)) // This middleware is needed do handle the errors thrown by the handler
```
[![npm version](https: