我有一个带有REST控制器的Spring web应用程序,如下所示:
@RequestMapping(value = "/something", method = RequestMethod.PUT)
public @ResponseBody ResponseEntity<Resp> do(@Valid @RequestBody(required = true) Body b){
我的对象有这样的验证:
public class Body implements Serializable {
@NotEmpty
@Max(value = 32)
private String nss;
我的@ExceptionHandler是这样的:
@ControllerAdvice
public class Handler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = { MethodArgumentNotValidException.class })
public ResponseEntity<RespError> invalidInput(RuntimeException ex) {
RespErrorresponse = new RespError();
return new ResponseEntity<RespError>(response, HttpStatus.BAD_REQUEST);
}
我试图捕捉无效的异常,但每次我试图启动应用程序时,我都会得到:
java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]: {public org.springframework.http.ResponseEntity com.algoApp.controller.RestResponseEntityExceptionHandler.invalidInput(java.lang.RuntimeException), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest) throws java.lang.Exception}
我应该如何实现处理程序来捕获此异常
根据我的经验,匹配参数是可行的。
@ControllerAdvice
public class Handler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = { MethodArgumentNotValidException.class })
public ResponseEntity<RespError> invalidInput(MethodArgumentNotValidExceptionex) {
RespErrorresponse = new RespError();
return new ResponseEntity<RespError>(response, HttpStatus.BAD_REQUEST);
}
}