SpringMvc异常处理

左心房为你撑大大i 提交于 2020-01-29 13:46:30

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"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!