java

SpringMVC 全局异常处理

2019-03-11  本文已影响0人  二妹是只猫
创建ExceptionResolver实现HandlerExceptionResolver接口:
@Slf4j
@Component
public class ExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.error("{} Exception",request.getRequestURI(),ex);
        ModelAndView modelAndView = new ModelAndView(new MappingJacksonJsonView());

        //使用MappingJackson2JsonView需要Jackson 2.x,这里引入的jackson是1.9版本,
        modelAndView.addObject("status",ResponseCode.ERROR.getCode());
        modelAndView.addObject("msg","接口异常,详情查看服务端日志");
        modelAndView.addObject("data", ex.toString());
        return modelAndView;
    }
}
在dispatcher-server中添加扫描:
<context:component-scan base-package="com.mmall.controller" annotation-config="true" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

直接扫描到controller下的controller注解。

创建接口用于异常测试:
    @RequestMapping(value = "test_error.do",method =  RequestMethod.GET)
    @ResponseBody
    public void testError(){
        int a = 0;
        int b = 500/a;
    }

接口请求返回到异常信息:

error
上一篇下一篇

猜你喜欢

热点阅读