catch函数的HttpException参数的名为message的属性没有statusCode

时间:2018-12-17 23:31:08

标签: nestjs

当我返回400错误时,catch函数的HttpException参数的名为message的属性

[
 {
  "target": {
    "password": "xxxxxx"
  },
  "property": "
  "children": [],
  "constraints": {
    "maxLength": "Este campo no debe tener mas de 30 caracteres",
    "isString": "Este campo debería contener un string",
    "isNotEmpty": "Este campo no puede estar vacío"
  }
 }
]

但是我希望收到

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": [
   {
    "target": {
      "password": "xxxxxx"
    },
    "property": "
    "children": [],
    "constraints": {
      "maxLength": "Este campo no debe tener mas de 30 caracteres",
      "isString": "Este campo deberia contener un string",
      "isNotEmpty": "Este campo no puede estar vacío"
    }
   }
  ]
 }

通过说明将问题最小化

@Catch(HttpException)
export class ExceptionHandler implements ExceptionFilter {

  catch(exception: HttpException, host: ArgumentsHost) {
    ...
    const statusCode = exception.message.statusCode;//undefined
    ...

    response
    .status(statusCode)//so here there is an error
    .json(json);
  }
}



@Controller('user')
export class UserController {

  @Post('create')
  create(@Body() user: User) {//the error occurred when the user 
                                object do not pass validations
    return user;
  }

  ...
}



export class User {

  readonly id: number;

  @IsNotEmpty({ message: TXT_14 })
  @IsString({ message: TXT_15 })
  @MaxLength(30, { message: TXT_16 })
  readonly username: string;

  @IsNotEmpty({ message: TXT_14 })
  @IsString({ message: TXT_15 })
  @MaxLength(30, { message: TXT_16 })
  readonly password: string;
}

引发错误

stacktrace

环境

嵌套版本:5.4.0

对于工具问题:

  • 节点版本:10.9.0
  • 平台:Mac

对不起,我的英语不好:)

0 个答案:

没有答案