我想使用Spring AOP封装所有控制器方法以进行错误处理。
但是,如何正确地将catch块中的e.getMessage()发送到error.html中的$ {errorMessage}?
感谢您的回复!
@Pointcut("within(com.test.mvc.controller.*) && @within(org.springframework.stereotype.Controller)")
public void controllerLayer() {
}
@Pointcut("execution(public String *(..))")
public void publicMethod() {
}
@Pointcut("controllerLayer() && publicMethod()")
public void controllerPublicMethod() {
}
@Around("controllerPublicMethod()")
public String processRequest(ProceedingJoinPoint joinPoint) {
try {
return (String) joinPoint.proceed();
} catch (Throwable e) {
LOGGER.info("{}", e.getMessage());
return "error.html";
}
}
<body>
<h1>Something went wrong!</h1>
<h3 th:text="'Error Message: ' + ${errorMessage}"></h3>
</body>
以下方面可以将请求属性设置为显示errorMessage。
@Around("controllerPublicMethod()")
public Object processRequest(ProceedingJoinPoint joinPoint) {
Object object=null;
try {
object = joinPoint.proceed();
} catch (Throwable e) {
RequestContextHolder.getRequestAttributes().setAttribute("errorMessage",e.getMessage(),0); // scope 0 - request , 1 - session
return "error.html";
}
return object;
}
我建议您请探索@ControllerAdvice
的可能性