springmvc exception handling based on aop

      When writing programs, exceptions are generally handled through try...catch...finally, but can we really handle all possible exceptions when writing programs? And what logic to execute when an exception occurs, what prompt information to return, and what page to jump to, these must be considered.

    The previous chapter introduced exception handling based on @ControllerAdvice (enhanced controller)

    Please refer to http://gsshijun.iteye.com/admin/blogs/2321980

   Here are some ways to handle exceptions based on spring aop:
1. Add pom

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-aop</artifactId>  
</dependency>

 
2. Reference example

/**
 * Exception interception handling
 * @author ThinkPad
 *
 */
@Aspect  
@Component
public class ExceptionInterceptor {
	//Intercept all methods under all classes under the com.sjz.cnmtc.web.main package and its subpackages
	@Pointcut("execution(* com.sjz.cnmtc.web.main..*.*(..))")
	private void myPointcut() {
		
	}
	
	@AfterThrowing(throwing="ex" , pointcut="myPointcut()")  
	public void doRecoveryActions(Throwable ex){  
		System.out.println("Exception thrown in target method: " + ex);
		writeContent("Exception thrown in target method");
	}
	
	/**
	 * output content to browser
	 *
	 * @param content output content
	 */
	private void writeContent(String content) {
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//        response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "text/plain;charset=UTF-8");
		response.setHeader("icop-content-type", "exception");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace ();
		}
		writer.print(content);
		writer.flush();
		writer.close();
	}
}

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326570533&siteId=291194637