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"/>
posted @ 2016-12-13 17:35  fengzp  阅读(867)  评论(0编辑  收藏  举报