• SpringMvc异常处理


    1、HandlerExceptionResolver实现

    这里是编写一个全局的异常处理器,其中分别处理ajax请求和页面请求的异常,ajax请求则返回错误信息,页面请求则跳转到500.jsp

    1.1实现HandlerExceptionResolver接口

    public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalHandlerExceptionResolver.class);
    
    @Override
    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object o, Exception ex) {
        boolean isAsync = req.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(req.getHeader("X-Requested-With").toString());
    
        if(isAsync) {
        	//WebTransException是自定义异常
            if (ex instanceof WebTransException) {
                WebTransException webTransException = (WebTransException) ex;
                printWrite(webTransException.getResponseMsg(), resp);
                logger.warn("ajax warn - [{}]", webTransException.getResponseCode()+":"+webTransException.getResponseMsg());
            }else {
                ex.printStackTrace();
                printWrite("系统异常!", resp);
            }
    
            return new ModelAndView();
        }
    
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error/500");
    
        if(ex instanceof WebTransException)
            modelAndView.addObject("WebTransException", ex);
        else
            ex.printStackTrace();
    
        return modelAndView;
    }
    
    public void printWrite(String msg, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=UTF-8");
    
            PrintWriter pw = response.getWriter();
            pw.write(msg);
            pw.flush();
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }
    

    1.2页面ajax弹出错误信息

    function deleteUser() {
        alert(${result["id"]});
    
        $.ajax({
            timeout : 20000,
            type : "POST",
            dataType : "json",
            url : url,
            data : data,
            success : function(data) {
                alert(data);
            },
            error : function(data) {
    //         data.responseText就是后台返回的错误信息
                alert(data.responseText);
            }
        });
    }
    

    1.3把处理器加到配置文件

    <bean id="globalHandlerExceptionResolver" class="com.yitop.admin.ctrl.GlobalHandlerExceptionResolver"/>
  • 相关阅读:
    商业分析07_15辅助产品设计
    商业分析07_14行为序列的分析方法
    商业分析07_13路径挖掘的分析方法
    商业分析07_12精准运营推送
    商业分析07_11归因查找
    商业分析07_10高质量拉新
    商业分析07_08功能/内容上线的评估
    商业分析07_07用户留存分析
    Ubuntu14.04安装CUDA8.0与Cudnn5.1
    Windows编译libcaffe时报cudnn.hpp(114): too few arguments in function call错误
  • 原文地址:https://www.cnblogs.com/andyfengzp/p/6170827.html
Copyright © 2020-2023  润新知