【问题标题】:Spring boot rest API @Valid @ExceptionHandler only working inside RestControllerSpring boot rest API @Valid @ExceptionHandler 仅在 RestController 内部工作
【发布时间】: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


【解决方案1】:

尝试使用@ExceptionHandler(value = BindException.class)

【讨论】:

    【解决方案2】:

    正如Spring Docs中提到的那样:

    使用此/其中一个注释注释的控制器将由 @ControllerAdvice 注释类辅助。

    尝试设置ControllerAdvice注解的annotations元素。

    @ControllerAdvice(annotations = RestController.class)
    

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 2020-10-04
      • 2018-06-23
      • 2017-10-18
      • 2021-11-02
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 2019-06-28
      相关资源
      最近更新 更多