Search code examples
javascripttypescriptnestjs

Circular JSON stringify error without relevant stack trace on Nest.js


The following error is killing my application in production:

/usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137
            ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value) => typeof value === 'bigint' ? value.toString() : value, 2)}\n`
                                                             ^

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'ClientRequest'
    |     property 'socket' -> object with constructor 'Socket'
    --- property '_httpMessage' closes the circle
    at JSON.stringify (<anonymous>)
    at ConsoleLogger.stringifyMessage (/usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137:62)
    at ConsoleLogger.formatMessage (/usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:130:29)
    at /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:122:43
    at Array.forEach (<anonymous>)
    at ConsoleLogger.printMessages (/usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:117:18)
    at ConsoleLogger.error (/usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:44:14)
    at Logger.error (/usr/src/app/node_modules/@nestjs/common/services/logger.service.js:34:75)
    at Logger.descriptor.value (/usr/src/app/node_modules/@nestjs/common/services/logger.service.js:163:27)
    at ExceptionsHandler.handleUnknownError (/usr/src/app/node_modules/@nestjs/core/exceptions/base-exception-filter.js:54:43)

I can't reproduce it on development and I don't know what is causing this error. Is there any way to make the stack trace include the source of this error?

I already ran it with DEBUG=*, but it doesn't give me a conclusive answer.

I think the error is happening close to these lines (based on logs), but I can't tell for sure:

      this.logger.error(error.toString())
      throw new InternalServerErrorException(error.toString())

It doesn't seems to be related, because error.toString() evaluates to [object Object] (useless, but not wrong).


Solution

  • Based on the properties, it looks like probably an AxiosError or some other HTTP client error was thrown directly without being converted into an HttpException that Nest would know how to handle and Nest then tried to log out the error. I would check your uses of HttpService (if you use it) or any other HTTP clients you use. If you still can't find anything, I'd suggest using a different logger than Nest's that can handle circular JSON. My preference is ogma, but I'm also the author of it. pino is another good choice