【发布时间】:2021-04-10 23:17:01
【问题描述】:
我有一个带有 ControllerAdvise 的 ControllerExceptionHandler ,当在应用程序中抛出 generalException 或 customException 时,我除了在这个 ControllerExceptionHandler 中捕获它。但它不会发生。它看起来很简单,阅读了很多网站,但它没有触发。 不知道问题出在哪里。
是ControllerExceptionHandler.class
@ControllerAdvice
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ControllerExceptionHandler.class);
@ExceptionHandler(Exception.class)
public final ResponseEntity<?> handleGeneralErrors(Exception e, UserPrincipal userPrincipal) {
if (e instanceof ClientAbortException) {
LOGGER.error("REST client abort: {}", e.getMessage());
} else {
LOGGER.error("REST controller error.", e);
}
//somelogic
return new ResponseEntity<>(responseObject, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(MyCustomException.class)
public final ResponseEntity<?> handleCustomErrors(MyCustomException e, UserPrincipal userPrincipal) {
LOGGER.error("MyCustomException error.", e);
return new ResponseEntity<>(
responseObject,
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
控制器类
@RestController
@RequestMapping(path = "/rest/test", produces = MediaType.APPLICATION_JSON_VALUE)
public class Controller {
private static final Logger LOGGER = LoggerFactory.getLogger(Controller .class);
@Autowired
private SomeLogicClass someLogicClass;
@GetMapping("/check")
@ResponseBody
public ResponseEntity<List<City>> list(UserPrincipal userPrincipal) throws Exception {
//Some logic
return ResponseEntity.ok(someLogicClass.handleRequest());
}
SomeLogicClass.class
@Service
public class SomeLogicClass{
public void handleRequest() throws Exception {
//some logic
} catch (Exception ex) {
throw new MyCustomException();
}
}
}
所以,当请求到达 SomeLogicClass 时,会抛出一些异常(例如 NPE),然后我想抛出 catch myCustomException。我希望它会转到 ControllerAdvise,但什么也没有,我看到错误 500。 这里缺少什么或什么? Controller 和 ControllerAdvise 位于某个包中。
我也尝试添加包
@ControllerAdvice("my.package.controller")
【问题讨论】:
-
好吧,你的
MyCustomException正在抛出一个INTERNAL_SERVER_ERROR,这是一个500。这有帮助吗? -
是的,我理解你正在抛出 INERNAL_SERVER_ERROR,但是当我在调试时,它不会进入这个方法:
@ExceptionHandler(MyCustomException.class) public final ResponseEntity<?> handleCustomErrors(MyCustomException e, UserPrincipal userPrincipal) { LOGGER.error("MyCustomException error.", e); return new ResponseEntity<>( responseObject, HttpStatus.INTERNAL_SERVER_ERROR); }我的意思是我在这个上面放了断点,它永远不会停止在线LOGGER.error("MyCustomException error.", e); -
我还将 ResponseError 更改为与 INTERNAL_SERVER_ERROR 不同的其他内容,我再次得到 500 。它甚至没有到达街区。
标签: java spring spring-boot spring-mvc controller