Created
March 9, 2021 08:14
-
-
Save crunchie84/6cf5c5d2fa59dd5f4f3bd62ed6e4512c to your computer and use it in GitHub Desktop.
Middy setup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Implementation based on https://github.com/middyjs/middy/blob/master/src/middlewares/httpErrorHandler.js | |
* | |
* Business rules: | |
* - Will always return 500 on errors | |
* - Will log with users emailaddress if possible | |
*/ | |
export function errorHandler(opts) { | |
const defaults = {logger: console.error}; | |
const options = Object.assign({}, defaults, opts); | |
const logger = typeof options.logger === 'function' | |
? options.logger | |
: () => {};//fallback: no-op | |
return ({ | |
onError: (handler, next) => { | |
let userEmailAddress = 'unknown'; | |
const authorizer = handler.event.requestContext.authorizer; | |
if (authorizer && authorizer.email) { | |
userEmailAddress = authorizer.email; | |
} | |
logger( | |
`Error during handling of request: ${handler.error.message}`, | |
{ user: userEmailAddress }, | |
handler.error | |
); | |
// enrich response with at least the explicit error body + status code | |
handler.response = Object.assign( | |
{}, | |
handler.response || {}, | |
{ | |
statusCode: 500, | |
body: JSON.stringify({ error: true }), | |
} | |
); | |
return next(); | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// lazy loading of the middy stack so we can inject stubs during testing if needed before the whole middyfy has been wired | |
export function handler(event, context, callback) { | |
return middy(myLambdaBusinessLogicHandler) | |
.use(httpHeaderNormalizer()) // middy default | |
.use(correlationIds()) //https://www.npmjs.com/package/@dazn/lambda-powertools-correlation-ids | |
.use(assertAuthorizerExecuted()) | |
.use(jsonBodyParser()) // middy default | |
.use(errorHandler({logger: Log.error }))(event, context, callback); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment