The default springboot error is to jump to the error/Error page in the request return rendering path.
Source code analysis: 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); }For example, in application.properites, configure the rendering page as
#Configure freemakerspring.freemarker.template-loader-path=/WEB-INF/
If spring.freemarker.template-loader-path,springboot will look for the wrongly rendered page under the error file in templates in src/main/resources .
Then when an error occurs, the system will jump to the /WEB-INF/error/Error page.
Use AOP for web-layer exception handling
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 layer unified exception handling* * @author niugang * */@Aspect@Componentpublic class ExceptionControllerAscept { private Logger logger = LoggerFactory.getLogger(ExceptionControllerAscept.class); /** * Anonymous point-cutting method* * @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"); // First if it is RuntimeException if (ex instanceof RuntimeException) { logger.error("Throw runtime exception {}", ex.getMessage()); modelAndView.addObject("exception", ex.getMessage()); // Jump to the error page modelAndView.addObject("url", request.getRequestURL()); return modelAndView; } modelAndView.addObject("exception","Unknown exception"); return modelAndView; }}Summarize
The above is what the editor introduced to you about using AOP to handle web layer exceptions in Spring Boot. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!