【发布时间】:2017-11-01 19:43:41
【问题描述】:
我想在控制器级别验证 Spring rest api 的实体。 这是我的代码:
@RestController
@RequestMapping("/orgs")
public class OrganizationController {
@PostMapping("/")
public ResponseEntity<ValidationResponse> addOrganization(@Valid @RequestBody Organization organization){
//code here
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ValidationResponse> invalidInput(MethodArgumentNotValidException ex) {
ValidationResponse response = new ValidationResponse();
response.setSuccess(false);
response.setMessage(ex.getMessage());
return new ResponseEntity<ValidationResponse>(response, HttpStatus.BAD_REQUEST);
}
}
如果我在我的控制器类中包含 ExceptionHandler 它工作正常。但是,如果我将这个 exceptionHandler 移动到 @ControllerAdvice 中,如下所示它不起作用。
@ControllerAdvice
public class ExceptionHandlingController {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ValidationResponse> invalidInput(MethodArgumentNotValidException ex) {
ValidationResponse response = new ValidationResponse();
response.setSuccess(false);
response.setMessage(ex.getMessage());
return new ResponseEntity<ValidationResponse>(response, HttpStatus.BAD_REQUEST);
}
}
从控制台日志我发现它被扫描了:
ExceptionHandlerExceptionResolver - Detected @ExceptionHandler methods in defaultExceptionHandler
ExceptionHandlerExceptionResolver - Detected @ExceptionHandler methods in exceptionHandlingController
但是 ExceptionHandler 方法没有被调用。
我做错了吗?
【问题讨论】:
-
你有没有遇到类似这个帖子@ControllerAdvice exception handler method are not get called的问题?
-
@LHCHIN 我也尝试过 EnableWebMvc 但没有运气。在不添加 EnableWebMvc 的情况下,spring 组件扫描也会检测到 ExceptionHandler。但是方法没有被调用。我不明白是什么问题! :(
标签: spring-mvc spring-boot hibernate-validator spring-validator