我想使用带注释的“@ExceptionHandler”捕获 SpringMVC3 中的“错误”。我可以捕获可抛出异常和任何异常,但是当我尝试使用“Error”时,它没有捕获异常。知道为什么吗?下面的代码演示了这个问题。
@Controller
@RequestMapping("/test")
public class TestExceptionController {
static final Logger logger = Logger.getLogger(TestExceptionController.class);
@RequestMapping(method = RequestMethod.GET)
public String processData(int intValue) throws InvalidDataException {
if (intValue < 6) {
try {
throw new Exception();
} catch (Exception e) {
throw new InvalidDataException();
}
}
return "test";
}
@ExceptionHandler(InvalidDataException.class)
public ModelMap handleException(InvalidDataException ex) {
logger.debug("exception catched :" + ex);
return new ModelMap();
}
}
上面的代码捕获了,但是下面的代码没有捕获。为什么它没有捕获错误?
@Controller
@RequestMapping("/test")
public class TestExceptionController {
static final Logger logger = Logger.getLogger(TestExceptionController.class);
@RequestMapping(method = RequestMethod.GET)
public String processData(int intValue) throws Error{
if (intValue < 6) {
try {
throw new Exception();
} catch (Exception e) {
throw new Error();
}
}
return "test";
}
@ExceptionHandler(Error.class)
public ModelMap handleException(Error ex) {
logger.debug("exception catched :" + ex);
return new ModelMap();
}
}
实际上我查看了 spring DispatcherServlet 的源代码,在第 809 行它解释了为什么无法处理错误
catch (Exception ex) {
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
mv = processHandlerException(processedRequest, response, handler, ex);
errorView = (mv != null);
}
代码是 spring 处理 ExceptionResolvers 的部分,可能是基于注释的,也可能是基于 bean 的。可以看到Spring只抛出异常而不抛出Throwable。 Error 不是 Exception 的子类,而是可抛出的,所以你无法用 Spring 这种方式处理它。与此相关的是,该注释也称为@ExceptionHandler,因此它暗示它不适用于错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)