如何在Node/NestJS中修复"TypeError: Converting circular structure to JSON"错误?

8 浏览
0 Comments

如何在Node/NestJS中修复"TypeError: Converting circular structure to JSON"错误?

我正在尝试向cosmosDB容器中插入一条记录,但偶尔会出现TypeError: Converting circular structure to JSON的错误。我不确定这里的根本原因是什么。

此外,我尝试了一些其他的Stack Overflow建议,如下所示,但没有成功:

错误:

error - TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Timeout'
    |     property '_idlePrev' -> object with constructor 'TimersList'
    --- property '_idleNext' closes the circle
partnersusers   error (2022-07-11T16:10:39.402-04:00) error in create(): TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Timeout'
    |     property '_idlePrev' -> object with constructor 'TimersList'
    --- property '_idleNext' closes the circle - UsersRepository
partnersusers   error (2022-07-11T16:10:39.403-04:00) error while creating user - UsersService
partnersusers   error (2022-07-11T16:10:39.403-04:00) Error during user creation - TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Timeout'
    |     property '_idlePrev' -> object with constructor 'TimersList'
    --- property '_idleNext' closes the circle - UsersController
partnersusers   error (2022-07-11T16:10:39.419-04:00) Converting circular structure to JSON
    --> starting at object with constructor 'Timeout'
    |     property '_idlePrev' -> object with constructor 'TimersList'
    --- property '_idleNext' closes the circle

代码:

users.controller.ts:

  @Post()
  async create(@Body() createUserDto: CreateUserDto): Promise {
    try {
      const token: Token = await this.getToken();
      const authUser = await this.authService.createAuthUser(
        createUserDto,
        token,
      );
      const response: User = await this.usersService.create(
        createUserDto,
        authUser,
      );
      const transformedUser: User = await this.transformUser(response);
      this.logService.log(
        `user created successfully - ${this.constructor.name}`,
        transformedUser,
        'create',
      );
      return transformedUser;
    } catch (error) {
      this.logService.error(
        `Error during user creation - ${error} - ${this.constructor.name}`,
        error,
        'create',
      );
      throw error;
    }
  }

users.service.ts:

  async create(
    createUserDto: CreateUserDto,
    authUser: CreateUser,
  ): Promise {
    try {
      const user: User = {
        id: authUser.user_id,
        contact: {
          firstName: createUserDto.contact.firstName,
          lastName: createUserDto.contact.lastName,
          email: createUserDto.contact.email,
          phoneNumber: createUserDto.contact.phoneNumber,
        },
        isReceiveText: createUserDto.isReceiveText,
        isSamePrimaryContactInfo: createUserDto.isReceiveText,
        primaryContact: {
          firstName: createUserDto.primaryContact.firstName,
          lastName: createUserDto.primaryContact.lastName,
          email: createUserDto.primaryContact.email,
          phoneNumber: createUserDto.primaryContact.phoneNumber,
        },
        businesses: createUserDto.businesses,
        audit: {
          createdOn: new Date(),
        },
        isActive: true,
      };
      const response = await this.userRepository.create(user);
      this.logService.log(
        `User created successfully - ${this.constructor.name}`,
        response,
        'create',
      );
      return response;
    } catch (error) {
      this.logService.error(
        `error while creating user - ${this.constructor.name}`,
        error,
        'create',
      );
      throw error;
    }
  }

users.repository.ts:

  async create(item: User): Promise {
    let response: User | ItemResponse | PromiseLike;
    // let response;
    try {
      console.log(`222 - ${JSON.stringify(item)}`);
      response = await this.container.items.create(item);
      // response = await this.container.items.upsert(item);
      this.logService.log(
        `User record created successfully - ${this.constructor.name}`,
        response,
        'create',
      );
      return response.resource;
    } catch (error) {
      console.log(`error - ${error}`);
      if (error.code !== 409) {
        this.logService.error(
          `error in create(): ${error} - ${this.constructor.name}`,
          error,
          'create',
        );
        throw error;
      }
      response = await this.findById(item.id);
      return response;
    }
  }

请求:(这是来自.repository.ts文件的console.log("222 - ${JSON.stringify(item)}");。即使在错误之后,我在容器中也看到了相同的记录。

{

"id": "someID",

"contact": {

"firstName": "John",

"lastName": "Doe",

"email": "john.doe3@gmail.com",

"phoneNumber": "123-456-7890"

},

"isReceiveText": false,

"isSamePrimaryContactInfo": false,

"primaryContact": {

"firstName": "John",

"lastName": "Doe",

"email": "john.doe@gmail.com",

"phoneNumber": "123-456-7890"

},

"businesses": [

{

"role": {

"type": "General Manager",

"services": [

{ "type": "Buy Inventory" },

{ "type": "Sell Inventory" }

]

}

}

],

"audit": { "createdOn": "2022-07-11T20:01:14.768Z" },

"isActive": true

}

0
0 Comments

问题出现的原因是返回了一个整个的cosmos对象,并尝试对其进行日志记录,这导致了错误的发生。这就是为什么记录被保存了,但仍然会出现错误的原因。换句话说,我看错了地方。

在repository中,我需要记录response.resource,而不是response对象。

解决方法如下(users.repository.ts):

async create(item: User): Promise {
    let response: User | ItemResponse | PromiseLike;
    // let response;
    try {
      console.log(`222 - ${JSON.stringify(item)}`);
      response = await this.container.items.create(item);
      // response = await this.container.items.upsert(item);
      this.logService.log(
        `User record created successfully - ${this.constructor.name}`,
        response.resource, //<----- FIX
        'create',
      );
      return response.resource;
    } catch (error) {
      console.log(`error - ${error}`);
      if (error.code !== 409) {
        this.logService.error(
          `error in create(): ${error} - ${this.constructor.name}`,
          error,
          'create',
        );
        throw error;
      }
      response = await this.findById(item.id);
      return response;
    }
  }

通过以上修改,问题应该得到解决。

0