springmvc全局异常处理

springmvc提供了全局异常处理器接口,只需要自定义一个异常处理器实现此接口.

public class GlobalExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {
		//判断异常的种类
		String msg = null;
		String ex = null;
		if (exception instanceof CustomerException) {
			CustomerException custExp = (CustomerException) exception;
			ex = custExp.getExpMessage();
			msg = custExp.getExpMessage();
		} else {
			//如果是自定义异常,取错误消息
			//如果是运行时异常,取错误的堆栈。
			exception.printStackTrace();
			StringWriter s = new StringWriter();
			PrintWriter printWriter = new PrintWriter(s);
			exception.printStackTrace(printWriter);
			ex = s.toString();
		}
		//写日志、发短信、发邮件
		logger.error("系统发生异常", ex);
		//...
		//返回一个错误页面,显示错误消息
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("msg", msg);
		modelAndView.setViewName("error");
		return modelAndView;
	}

}
参考:https://www.cnblogs.com/andy-zhou/p/5317820.html
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页