Java Spring 输入 Id 为字符串时发送 422 作为响应
Java Spring send 422 in response when input Id is string
我有一个 Rest 控制器,在我的控制器中我有显示单个用户记录的方法。考虑 url 是这样的:
/api/v1/users/{id}
这是我的方法
@GetMapping("/{id}")
@Operation(summary = "Show single user", security = @SecurityRequirement(name = "bearerAuth"))
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Found the User", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }),
@ApiResponse(responseCode = "404", description = "User not found", content = @Content)
})
public UserDto getUserById(@PathVariable Long id) throws ResourceNotFoundException {
return modelMapper.map(userService.findUserById(id), UserDto.class);
}
问题是当我发送“/api/v1/users/some-string”然后我得到 500,我该如何处理这个和 return 422 以及无效用户 ID 的消息?
您应该在您的控制器中或在单独的 class 注释 @ControllerAdvice
或 @RestControllerAdvice
中为 MethodArgumentTypeMismatchException
声明 @ExceptionHandler
方法,例如:
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
ApiError handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
// construct ApiError
// return ApiError
}
我有一个 Rest 控制器,在我的控制器中我有显示单个用户记录的方法。考虑 url 是这样的:
/api/v1/users/{id}
这是我的方法
@GetMapping("/{id}")
@Operation(summary = "Show single user", security = @SecurityRequirement(name = "bearerAuth"))
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Found the User", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }),
@ApiResponse(responseCode = "404", description = "User not found", content = @Content)
})
public UserDto getUserById(@PathVariable Long id) throws ResourceNotFoundException {
return modelMapper.map(userService.findUserById(id), UserDto.class);
}
问题是当我发送“/api/v1/users/some-string”然后我得到 500,我该如何处理这个和 return 422 以及无效用户 ID 的消息?
您应该在您的控制器中或在单独的 class 注释 @ControllerAdvice
或 @RestControllerAdvice
中为 MethodArgumentTypeMismatchException
声明 @ExceptionHandler
方法,例如:
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
ApiError handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
// construct ApiError
// return ApiError
}