Spring Boot handle exceptions @ ControllerAdvice + @ ExceptionHandler

1 Introduction       

MVC project, to provide a friendly user experience, as far as possible a comprehensive system logging, Controller usually capture business level exceptions, returns an error message to avoid unfriendly. Thus, the Controller each method is to use the template of the try-catch, process all exceptions, but results in poor maintenance codes unsightly. as follows:

		try {
			......
		} catch (Exception e) {
			......
		} finally {
			......
		}

@ControllerAdvice + @ExceptionHandler can use unified treatment Controller layer anomalies, avoid using the template of the try-catch, reducing these unnecessary code maintenance.

2. Define the global exception handler class

{Private static class GlobalExceptionHandler @ControllerAdvicepublic Logger Logger = LoggerFactory.getLogger (GlobalExceptionHandler.class);	 
	/ * 
	 * String to return data or data json: you need to annotate the method: add a return to @ResponseBody. 
	 * Back view: a ModelAndView to define, and then return; 
	 * define the view file (for example: error.html, error.ftl, the error.jsp); 
	 * / 
	@ExceptionHandler (Exception.class) 
	@ResponseBody public from exceptionHandler the Result <?> (Exception E) { 
		String e.toString MSG = (); 
		logger.error (MSG, E); return (<?> the Result) Result.toFail (MSG); 
	} 
	
}

Note: GlobalExceptionHandler should be included in the Application initiate a scan path in order to be loaded using incorrect.

3. deficiencies at

Controller can only handle exceptions thrown for Interceptor (Interceptor) and other abnormal levels, do nothing.

欢迎工作一到五年的Java工程师朋友们加入Java技术交流群:659270626
群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)合理利用自己每一分每一秒的时间来学习提升自己,不要再用"没有时间“来掩饰自己思想上的懒惰!趁年轻,使劲拼,给未来的自己一个交代!


Guess you like

Origin blog.51cto.com/14028890/2422754