【问题标题】:nestjsx/crud - how to change errors responsesnestjsx/crud - 如何更改错误响应
【发布时间】:2021-11-22 21:53:45
【问题描述】:

例如,我需要更改错误响应 404 错误。 这是de case:

@Entity('role')
export class RoleEntity extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'varchar', length: 100, nullable: false })
  name: string;
}

@Injectable()
export class RoleService extends TypeOrmCrudService<RoleEntity> {
  constructor(@InjectRepository(RoleEntity) repo) {
    super(repo);
  }
}

@Crud({
  model: {
    type: RoleEntity,
  },
})
@Controller('role')
export class RoleController implements CrudController<RoleEntity> {
  constructor(public service: RoleService) {}
}

当我尝试获取未在基础中创建的 id 时出现错误

{
  "statusCode": 404,
  "message": "RoleEntitynot found",
  "error": "Not Found"
}

我想把这个错误改成这样:

{
  "success": false,
  "message": "The given id was not found in the database",
}

最好的方法是什么?

【问题讨论】:

  • 很难理解你的服务在哪里,你的控制器在哪里。考虑使用适当的格式编辑问题。也尝试添加服务和控制器方法。
  • 此方法由 lib github.com/nestjsx/crud 生成,带有装饰器 @Crud。
  • 我的意思是分离你的服务和控制器。

标签: nestjs crud typeorm


【解决方案1】:

覆盖 nestjs/crud getOneBase 方法 (Doc nestjs/crud)

@Override('getOneBase')
getOneAndDoStuff(
    @ParsedRequest() req: CrudRequest,
    ) {
    // Catch below error and return your message
    this.base.getOneBase(req)

    return ...;
}

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2015-03-27
    • 2015-10-23
    • 1970-01-01
    • 2020-01-27
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    相关资源
    最近更新 更多