SpringMVC 自定义异常处理器

版权声明: https://blog.csdn.net/pbrlovejava/article/details/82079941

系统在故障时,为了能够及时地通知到相关技术人员进行维护,我们通常需要在控制层定义一个异常处理器,当异常层层抛出到控制层时进行捕获。

一、异常处理思路:

 二、自定义异常MyException:为了区别不同的异常,通常根据异常类型进行区分,这里我们创建一个自定义系统异常。

public class MyException extends Exception {
	// 异常信息
	private String message;

	public MyException() {
		super();
	}

	public MyException(String message) {
		super();
		this.message = message;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}

 三、自定义异常处理器CustomHandleException,所有的异常发生时都会通过它,一个系统中只能有一个异常处理器。

public class GlobalExceptionResolver implements HandlerExceptionResolver {
    
        Logger logger = LoggerFactory.getLogger(CustomHandleException.class);
        
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {
		// 定义异常信息
		String msg;

		// 判断异常类型
		if (exception instanceof MyException) {
			// 如果是自定义异常,读取异常信息
			msg = exception.getMessage();
		} else {
			// 如果是运行时异常,则取错误堆栈,从堆栈中获取异常信息
			Writer out = new StringWriter();
			PrintWriter s = new PrintWriter(out);
			exception.printStackTrace(s);
			msg = out.toString();

		}

		// 把错误信息发给相关人员,邮件,短信等方式
                //记录日志
                logger.error("系统发生异常", msg);
		// TODO

		// 返回错误页面,给用户友好页面显示错误信息
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("msg", msg);
		modelAndView.setViewName("error");

		return modelAndView;
	}
}

四、日志记录log4j.properties

# Configure logging for testing: optionally with log file
log4j.rootLogger=debug, stdout,D,E
# log4j.rootLogger=WARN, stdout, logfile
 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
 
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender  
log4j.appender.D.File = C://logs/GlobalException.log
log4j.appender.D.Append = true  
log4j.appender.D.Threshold = DEBUG   
log4j.appender.D.layout = org.apache.log4j.PatternLayout  
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n  
 
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender  
log4j.appender.E.File =C://logs/GlobalException.log   
log4j.appender.E.Append = true  
log4j.appender.E.Threshold = ERROR   
log4j.appender.E.layout = org.apache.log4j.PatternLayout  
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

五、在springmvc.xml中注册异常处理器

<!-- 全局异常处理器 -->
    <bean class="com.iteason.search.exception.GlobalExceptionResolver"/>

猜你喜欢

转载自blog.csdn.net/pbrlovejava/article/details/82079941