使用ControllerAdvice

时间:2016-08-26 04:25:44

标签: spring-mvc

我正在使用spring rest构建API并尝试验证输入参数,如下所示:

@RequestMapping("/myUrl")
@RestController
@Validated
public class MyController {

  @ResponseStatus(HttpStatus.OK)
  @RequestMapping(value = "getSomething", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
  public myResponse getMarketResult(
  @RequestParam @NotNull @NotBlank @NotEmpty String inputParam) {
    //...my implementation
  }
}

验证在所有这些场景中都有效(null,空白,空)。 抛出MissingServletRequestParameterException为null,抛出空白/空的ConstraintViolationException。

控制器建议:

@ControllerAdvice
public class ControllerValidationHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(NestedServletException.class)
  public ResponseEntity<Object> processValidationError(NestedServletException ex, HttpStatus status, WebRequest request) {
    // my implementation
  }

  @ExceptionHandler(ConstraintViolationException.class)
  public ResponseEntity<Object> processValidationError(ConstraintViolationException ex, HttpStatus status, WebRequest request) {
    // my implementation
  }

  @Override
  protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    // my implementation
  }

  @ExceptionHandler(Exception.class)
  public ResponseEntity<Object> handleExpception(HttpServletRequest req, Exception ex, WebRequest request) {
    // my implementation
  }

但是我观察到:

  1. 引发ConstraintViolationException是org.springframework.web.util.NestedServletException的原因。

  2. ControllerAdvice无法捕获ConstraintViolationException和NestedServletException(但MissingServletRequestParameterException有效),它现在返回一个html(而不是json)。

  3. 2个异常也不会被ResponseEntityExceptionHandler的'handleException'处理。

    如何解决1和2?我正在使用Spring版本4.3.1

    编辑1: 还有一个例子,如果我有这样的参数:

    @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @NotNull LocalDate localDate
    

    如果请求为空(例如'/ myURL / getSomething?localDate ='

    ,则会抛出(1)中提到的Expcetion

0 个答案:

没有答案