# 异常处理

# 异常定义

# 账号异常

  • UnAuthticatedException :未认证异常,也就是未登录。 code:-401
  • UnAuthorizedException :未授权异常,也就是不具备权限.code:-403
  • NonEnabledAccountException: 账户未启用,也就是 UserDetails 的 enabled=false.code:-998

# Session异常

  • ExpiredSessionException: Session 过期,code:-1000
  • InvalidSessionException :Session 错误,code:-999
  • CookieException :Cookie 处理出现错误

# 通用异常

  • ExcessiveAttemptsException : 登录次数超过限制异常.code:-423

# 异常处理

基于 Spring Boot ,Heimdall 框架实现了统一错误页面和异常处理 Advisor。

# 错误处理控制器:

源码: BaseServletErrorController.java

public class BaseServletErrorController extends BasicErrorController {
    /**
     * Instantiates a new Base servlet error controller.
     *
     * @param errorAttributes    the error attributes
     * @param serverProperties   the server properties
     * @param errorViewResolvers the error view resolvers
     */
    @Autowired
    public BaseServletErrorController(ErrorAttributes errorAttributes,
                                      ServerProperties serverProperties,
                                      List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, serverProperties.getError(), errorViewResolvers);
    }

    /**
     * 根据配置参数确定错误页面
     */
    @Value("${server.error.name:${error.name:error}}")
    public String errorView;
    。。。。。。。。
    }

错误处理控制器已通过BasicErrorControllerConfig进行自动配置。

错误处理控制器会自动根据请求数据格式判断是普通 html页面请求还是 json 请求,自动返回对应格式数据。

可通过server.error.name或者error.name参数来定义错误页面,默认错误页面,templates/error.html.

默认情况下,heimdall-starter-spring-boot已经提供了默认的错误页面。

# 全局异常处理 Advisor

全局异常处理基类,对常见的系统错误进行了统一拦截和处理,支持 JSON 和 html 自动判断协商。 具体实现参见源码:AbstractHeimdalExceptionAdvice.java

使用方式,扩展此类并配置即可,如下所示

@Slf4j
@ControllerAdvice
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionAdvice extends AbstractHeimdalExceptionAdvice {
	//........自己的处理逻辑
}
上次更新:: 1/25/2021, 4:26:40 PM