【问题标题】:NodeJS Mongoose : Catch CRUD Error and send back a custom message to clientNodeJS Mongoose:捕获 CRUD 错误并将自定义消息发送回客户端
【发布时间】:2021-01-05 05:29:56
【问题描述】:

环境

  • NodeJS 10
  • MongoDB
  • 客户端应用:Angular 9

说明

我在 NodeJS 端有一个控制器和一个服务,它们创建一个实体并发送回这样的承诺:

控制器

    async create(@Body() entityData: any) {
        return this.getService().create(entityData);
    }

服务


  newInstance(obj:any={}):T{
     return new (this.getRepository() as Model<T>)(obj);
  }


  async create(entityToCreate): Promise<T> {
    let toCreateUpdated = this.newInstance(entityToCreate);
    return toCreateUpdated.save(); //This returns a promise
  }

问题

有没有办法让我捕捉到重复字段之类的错误并将自定义消息发送回我的客户?

我尝试对 Promise 使用 try/catch 或仅 catch,但没有奏效。

提前谢谢你。

【问题讨论】:

    标签: javascript node.js angular mongoose


    【解决方案1】:
    async create(entityToCreate): Promise<T> {
        let toCreateUpdated = this.newInstance(entityToCreate);
     try {
        return await toCreateUpdated.save()
     } catch(error)
            console.log(error)
    }
    

    【讨论】:

    猜你喜欢
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2018-03-08
    • 2023-04-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多