springmvc处理异常有三种方式: 1.在一个controller中定义一个方法,用@ExceptionHandler注解标注。(优先级最高)
@ExceptionHandler
public
ModelAndView handleException(Exception exception){
ModelAndView mv =
new
ModelAndView(
"error/500"
);
mv.addObject(
"ex"
,exception);
return
mv;
}
@ExceptionHandler
public
String handleException(Exception exception){
return
"error/500"
;
}
2.全局异常设置(下载地址 优先级次之)
<!-- 将Controller抛出的异常转到特定View,异常映射处理器 -->
<bean
class
=
"org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"
>
<!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->
<!--<property name=
"exceptionAttribute"
value=
"ex"
></property>-->
<property name=
"exceptionMappings"
>
<props>
<prop key=
"java.lang.Throwable"
>error/
500
</prop>
</props>
</property>
</bean>
3.自定义异常处理(下载地址 优先级次之)
public
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
System.out.println(
"自定义异常处理器"
);
logger = LoggerFactory.getLogger(ex.getClass());
ResponseStatus responseStatus = AnnotationUtils.getAnnotation(ex.getClass(), ResponseStatus.
class
);
ModelAndView modelAndView =
new
ModelAndView(
"error/500"
);
//自定义的异常
if
(responseStatus !=
null
) {
modelAndView.setViewName(
"error/"
+ responseStatus.value().value());
}
else
{
//其他异常,做一些其他的处理,如发送错误报警邮件,记录日志
logger.error(ex.getMessage(), ex);
}
return
modelAndView;
}
4.自定义一个异常类,继承RunTimeException(优先级最低)
@ResponseStatus
(value = HttpStatus.NOT_FOUND,reason =
"No such resource"
)
public
class
NotFoundException
extends
RuntimeException {
}
当抛出我们自定义的异常时,就会构造出相应的状态码,一般我们还是设置SimpleMappingExceptionResolver,来进行统一跳转到错误页面。
最佳实践:还是用全局的SimpleMappingExceptionResolver最好,在jsp里面写日志,当需要进行细粒度的控制时,还是自定义异常解析器为好,其他的自我感觉不好用!如有不正确的,欢迎指正!