springboot 全局异常处理类
依赖
<!-- Spring Boot Web 依赖 核心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1、自定义一个 GlobalExceptionHandler 作为处理全局异常的处理类
2、类上加上 @ControllerAdvice 注解
3、在方法级别 加上 @ExceptionHandler 注解 与需要处理的类型
本类中有一个 运行时异常,还有一个 权限拦截异常
代码
package com.huayi.minprogramdemo.interceptor;
import com.huayi.minprogramdemo.utils.Res;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* @program: minprogram-demo
* @description: 全局异常处理类
* @author: Long Ao Tian
* @create: 2020-02-13 14:17
**/
@ControllerAdvice //拦截所有requestMapping
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理自定义的业务异常,没有权限
*
* @param request
* @param e
* @return
*/
// @ResponseStatus(value = HttpStatus.FORBIDDEN)
@ExceptionHandler(value = AccessDeniedException.class)
@ResponseBody
public Object AccessExceptionHandler(HttpServletRequest request, AccessDeniedException e) {
logger.error("发生业务异常!原因是:{},\n 具体错误在 {}", e, e.getStackTrace()[0] + "" + e.getStackTrace()[1]);
return Res.error(403, "没有权限访问");
}
/**
* 运行时异常的
*
* @param request
* @param e
* @return
*/
@ExceptionHandler(value = RuntimeException.class)
@ResponseBody
public Object defaultErrorHandler(HttpServletRequest request, RuntimeException e) {
// [0]
logger.error("发现运行时业务异常!原因是:{},\n 具体错误在 {}", e, e.getStackTrace()[0] + "" + e.getStackTrace()[1]);
return Res.error();
}
/**
* 404 异常
*
* @return
*/
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return (factory -> {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.do");
factory.addErrorPages(error404Page);
});
}
}