我正在为Spring MVC中的异常处理示例演示应用程序.我正在尝试 Exception Handling With @ControllerAdvice
我按照此链接中描述的步骤进行操作.
但是,当我运行我的应用程序时,我得到以下错误
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.test.core.ApplicationException
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅我正在处理的课程
ApplicationException.java
public class ApplicationException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = -9061684361606685158L;
private ErrorStatus errorStatus;
private int msgNumber;
private Object []args;
public ApplicationException(){}
public ApplicationException(ErrorStatus errorStatus, int msgNumber,
Object[] args) {
this.errorStatus = errorStatus;
this.msgNumber = msgNumber;
this.args = args;
}
//getter setters
}
Run Code Online (Sandbox Code Playgroud)
控制器类
ApplicationExceptionController.java
@Controller
@RequestMapping("/exception")
public class ApplicationExceptionController {
@RequestMapping(value="/error",method=RequestMethod.GET)
@ResponseBody
public void helloException() …Run Code Online (Sandbox Code Playgroud) 我想在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在控制器类中包含 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);
}
}
Run Code Online (Sandbox Code Playgroud)
从控制台日志我发现它被扫描了:
ExceptionHandlerExceptionResolver - Detected @ExceptionHandler methods in defaultExceptionHandler
ExceptionHandlerExceptionResolver - Detected …Run Code Online (Sandbox Code Playgroud)