(fastify, _options, done)
| 18 | * @param done Callback to signal that the logic has completed. |
| 19 | */ |
| 20 | const errorHandling: FastifyPluginCallback = (fastify, _options, done) => { |
| 21 | Sentry.setupFastifyErrorHandler(fastify); |
| 22 | |
| 23 | fastify.decorate('Sentry', Sentry); |
| 24 | |
| 25 | fastify.setErrorHandler((error: FastifyError, request, reply) => { |
| 26 | const logger = fastify.log.child({ req: request }); |
| 27 | const accepts = request.accepts().type(['json', 'html']); |
| 28 | const { returnTo } = getRedirectParams(request); |
| 29 | |
| 30 | if (!reply.statusCode || reply.statusCode === 200) { |
| 31 | const statusCode = |
| 32 | error.statusCode && error.statusCode >= 400 ? error.statusCode : 500; |
| 33 | reply.code(statusCode); |
| 34 | } |
| 35 | |
| 36 | const isCSRFError = |
| 37 | error.code === 'FST_CSRF_INVALID_TOKEN' || |
| 38 | error.code === 'FST_CSRF_MISSING_SECRET'; |
| 39 | |
| 40 | if (!isCSRFError) { |
| 41 | if (reply.statusCode >= 500) { |
| 42 | logger.error(error, 'Error in request'); |
| 43 | } else { |
| 44 | logger.warn(error, 'CSRF error in request'); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | const message = |
| 49 | reply.statusCode === 500 || isCSRFError |
| 50 | ? 'flash.generic-error' |
| 51 | : error.message; |
| 52 | if (accepts === 'json') { |
| 53 | void reply.send({ |
| 54 | message, |
| 55 | type: 'danger' |
| 56 | }); |
| 57 | } else { |
| 58 | void reply.status(302); |
| 59 | void reply.redirectWithMessage(returnTo, { |
| 60 | type: 'danger', |
| 61 | content: message |
| 62 | }); |
| 63 | } |
| 64 | }); |
| 65 | |
| 66 | done(); |
| 67 | }; |
| 68 | |
| 69 | export default fp(errorHandling, { |
| 70 | dependencies: ['redirect-with-message', '@fastify/accepts'] |
nothing calls this directly
no test coverage detected