這篇文章主要為大家展示了“Spring Boot中如何使用AOP統一處理web層異?!?,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“Spring Boot中如何使用AOP統一處理web層異?!边@篇文章吧。
在springboot錯誤默認是跳轉到 請求返回渲染路徑中的error/錯誤頁面中。
源碼分析:DefaultErrorViewResolver.java
private ModelAndView resolve(String viewName, Map<String, Object> model) {
String errorViewName = "error/" + viewName;
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders
.getProvider(errorViewName, this.applicationContext);
if (provider != null) {
return new ModelAndView(errorViewName, model);
}
return resolveResource(errorViewName, model);
}比如在application.properites中配置渲染頁面為
#配置freemaker spring.freemarker.template-loader-path=/WEB-INF/
如果不配置spring.freemarker.template-loader-path,springboot會在src/main/resources中的templates中的error文件下下找錯誤渲染的頁面。
那么當出現錯誤時,系統會跳轉到/WEB-INF/error/錯誤頁面中。

使用AOP進行web層異常處理
package com.niugang.aop;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
/**
* controller層統一異常處理
*
* @author niugang
*
*/
@Aspect
@Component
public class ExceptionControllerAscept {
private Logger logger = LoggerFactory.getLogger(ExceptionControllerAscept.class);
/**
* 匿名切點的方式
*
* @param ex
* @throws ServletException
* @throws IOException
*/
@AfterThrowing(value = "execution(public * com.niugang.controller..*.*(..))", throwing = "ex")
public ModelAndView aroundAdvice(Exception ex) throws ServletException, IOException {
ModelAndView modelAndView = new ModelAndView();
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes r = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = r.getRequest();
modelAndView.setViewName("500");
// 第一如果是 RuntimeException
if (ex instanceof RuntimeException) {
logger.error("拋出運行時異常{}", ex.getMessage());
modelAndView.addObject("exception", ex.getMessage());
// 跳轉到錯誤頁面
modelAndView.addObject("url", request.getRequestURL());
return modelAndView;
}
modelAndView.addObject("exception","未知異常");
return modelAndView;
}
}以上是“Spring Boot中如何使用AOP統一處理web層異?!边@篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。