Build logger, handle exception exception in NestJS

Tram Ho

Introduce

In Backend applications centralized logger handling and exception handling are important for error handling and troubleshooting. NestJS has provided some modules, we can implement arbitrary according to the logic we want.

Logger

NestJS has provided a set of text-base loggers, which are used during bootstraping, in other cases such as displaying exceptions.

Basic

In some cases and depending on the project we use some other log sets like Winston:

You can turn off, or specify the log level right from the bootstraping process of the application

Determine the log level at the time of bootstraping:

Log levels are supported: log , error , warn , debug , verbose

Custom

NestJS provides pre base class LoggerService and Logger , we can LoggerService some log levels.

For example

Building log module

DI (Dependency injection)

As you know, NestJS is built according to DDD model, the project will be divided into small modules. I will build a module specializing in handling log problems, from which I can inject into other modules.

Create class LoggerService

Create the logger module

Application logging

After building the Log Module, to use we just need to inject the module into any context, controller. For example Inject logger to controller

Exception

After the logger has been built, this time it is the Exception Handling section. Basically, all unhandled exceptions in the code will be concentrated on this layer

Here I will distinguish two main exception types, that is Built-in Error and HttpException After catching the exception, will proceed to get error message, status code. Here I have injected Logger service into class AllExceptionFilter , when catching exception other than repsone on client side, I will write to log.

Above, I have briefly summarized the process of building the log and handling the exception exception, details you can refer to repo: https://github.com/hoangtm1601/nest-base

Share the news now

Source : Viblo