1.spring设置全局异常,它的原理是向上捕获
spring.xml配置
<!--自定义全局异常处理器--> <bean id="globalExceptionResolver" class="com.data.controller.exception.GlobalExceptionResolver"/>
import com.data.service.email.EmailMessage; import com.data.utils.constant.AliasConstant; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; @Controller public class GlobalExceptionResolver implements HandlerExceptionResolver { @Resource EmailMessage emailMessage; /** * 进行全局异常过滤并处理 * * @param request action 请求 * @param response 服务器响应 * @param handler 发生错误的事件句柄 * @param ex 异常情况 * @return 视图&对象 */ @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //使用StringBuilder提搞GC回收效率,降低垃圾回收开销 StringBuilder content = new StringBuilder("<++>AllInOne-busWeb抓捕到异常具体内容信息:<++> "); String userId = (String) request.getSession().getAttribute(AliasConstant.UserId); content.append("造成该异常的用户userID为: " + userId + " "); content.append("爆出异常的类型为: " + ex.getClass() + " "); content.append("异常发生的位置为: " + handler + " "); content.append("造成的原因: " + ex.getMessage() + " "); content.append("造成的详细原因为: "); StackTraceElement[] trace = ex.getStackTrace(); for (StackTraceElement traceElement : trace) content.append("at " + traceElement + " "); return null; } }