Springmvc已经自带了全局异常处理类HandlerExceptionResolverComposite 实现了接口HandlerExceptionResolver 、Ordered

HandlerExceptionResolver 主要定义了异常处理方法 其中 e 就是controller内的方法处理时抛出的异常,也就是我们需要处理的地方

	
    public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception e) {
        return super.resolveException(arg0, arg1, arg2, e);
    }

正常的返回结果是ModelAndView 可用设置需要的视图和model对象,我这里只想返回json字符串所以实现方法为

  @Override
    public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception e) {
        if (e!=null) {
            RestInfo ri=new RestInfo(e.getMessage());
            Map<String, Object> model=new HashMap<String, Object>();
            model.put("body", ri.getBody());
            model.put("errMsg", ri.getErrMsg());
            model.put("status", ri.getStatus());
            MappingJackson2JsonView v=new MappingJackson2JsonView();
            v.setAttributesMap(model);
            return new ModelAndView(v);
        }
        return super.resolveException(arg0, arg1, arg2, e);
    }

自己用map拼接出规范的数据格式返回

效果:Springmvc 全局异常处理,返回json字符串

相关文章:

  • 2021-05-27
  • 2021-07-25
  • 2021-08-30
  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
  • 2022-02-09
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-07
  • 2021-04-03
  • 2021-07-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案