spring mvc 全局异常
客户端请求controller,为了不让异常返回到客户端,需把controller层的异常拦截掉,对异常进行包装然后再返回到客户端。
图解:
<context:component-scan base-package="cn.it.controller" annotation-config="true" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
可以自己加运行时异常进行测试:
int a = 0;
int b = 66 / a;
这个就是运行时异常,只有在运行时才会报出来。
在common包里建工具类ExceptionResolver 并加component注解就好了:
@Slf4j
@Component
public class ExceptionResolver implements HandlerExceptionResolver{
public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
Exception arg3) {
log.error("{} exception", arg0.getRequestURI(),arg3);//这一行要写,不然在服务端也看不到异常信息了。
ModelAndView modelAndView = new ModelAndView(new MappingJacksonJsonView());//当使用jackson2.x时使用MappingJackson2JsonView,这里使用的是1.9
modelAndView.addObject("status", ResponseCode.ERROR.getCode());
modelAndView.addObject("msg", "接口异常,详情请查看日志中的异常信息");
modelAndView.addObject("data",arg3.toString());
return modelAndView;
}
}