-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add unhandledExceptionPlugin (#91)
Co-authored-by: Igor Savin <[email protected]>
- Loading branch information
Showing
4 changed files
with
112 additions
and
3 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import type { ErrorReporter } from '@lokalise/node-core' | ||
import type { FastifyInstance } from 'fastify' | ||
import fp from 'fastify-plugin' | ||
|
||
export type ErrorObjectResolver = (err: unknown, correlationID?: string) => unknown | ||
|
||
export interface UnhandledExceptionPluginOptions { | ||
errorObjectResolver: ErrorObjectResolver | ||
errorReporter: ErrorReporter | ||
} | ||
|
||
function plugin(app: FastifyInstance, opts: UnhandledExceptionPluginOptions) { | ||
// Handle unhandled exceptions | ||
process.on('uncaughtException', (err) => { | ||
const logObject = opts.errorObjectResolver(err) | ||
app.log.fatal(logObject, 'uncaught exception detected') | ||
opts.errorReporter.report({ error: err }) | ||
|
||
// shutdown the server gracefully | ||
app.close(() => { | ||
process.exit(1) // then exit | ||
}) | ||
}) | ||
} | ||
|
||
export const unhandledExceptionPlugin = fp(plugin, { | ||
fastify: '4.x', | ||
name: 'unhandled-exception-plugin', | ||
}) |
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