我有此代码:
@GetMapping(value = "/users/{id}")
@ResponseStatus(HttpStatus.OK)
public DtoUser getUserById( @PathParam("id") @PathVariable("id") @RequestParam Long id) {
return adminService.getUserById(id);
}
和此代码:
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Override
public ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return error_with_my_info;
}
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(
MissingServletRequestParameterException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {{
return error_with_my_info;
}
...
}
问题是,当我发送不带参数的请求时,调用的是 handleHttpMessageNotReadable ,而不是 handleMissingServletRequestParameter 。 这是为什么? 其他API端点是否可以影响此行为,例如使PUT请求处理程序具有相同的端点? 我该如何做到 handleMissingServletRequestParameter ?
答案 0 :(得分:1)
即兴:
@GetMapping(value = "/users")
@ResponseStatus(HttpStatus.OK)
public DtoUser getUserById( @RequestParam(value="id" , required=true)Long id) {
return adminService.getUserById(id);
}
localhost:8080?id = test 现在,如果您不传递ID,它将为您提供handleMissingServletRequestParameter。