typescriptnestjs

How to log all exceptions to a custom logger in nest.js?


I have a custom logging service which outputs structured logs in a way that can be shipped to a third party log collection service.

I'm wondering what the best way to make sure that I catch all errors, from HTTP errors, to unhandled JS errors (e.g. TypeErrors, Uncaught Rejected Promises, etc), and ship them to said logger.

Most of the examples I have seen address HTTP errors only.


Solution

  • You can probably have a look to the uncaughtException here but it’s not related to nestjs

    https://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexception

    But be careful because you can corrupt the stability of your app

    EDIT

    You can take advantage of the global filters as describe here https://docs.nestjs.com/exception-filters

    App.useGlobalFilters(new MyFilter())
    

    And if you want to use DI you can add them into the appModule in the providers collection as a custom provider using the token

    Provide: APP_FILTER,
    useClass: MyFilter