文章目录
一、出现原因
在 AuthorizingRealm doGetAuthenticationInfo 中抛出异常
案例:
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken){
String token = (String) authenticationToken.getCredentials();
if(true){
throw new BusinessException("报错");
}
结果:
{
"timestamp": "2021-01-09T13:11:56.348+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Authentication failed for token submission [com.cancan.daxiangerp.utils.JWTToken@79e56cc5]. Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).",
"path": "/user/dx-user/query"
}
二、当我们创建全局拦截失败
例如 @RestControllerAdvice 进行全局捕获
/**
* 捕捉业务相关异常
*/
@ExceptionHandler(BusinessException.class)
public JsonResult handle10000(BusinessException e) {
log.error("异常{}的信息为:{}",HttpCodeEnum.BUSINESS_ERROR.getCode(),e.getMessage());
return new JsonResult(HttpCodeEnum.BUSINESS_ERROR.getCode(), e.getMessage(), null);
}
注意: 全局捕获失败
- 结论:
外部无法捕捉doGetAuthenticationInfo方法抛出的异常,原因在于源码,而不是自己的代码有问题。
如果没有改写源码的本事,那么外部想要捕捉各种异常,并在前端显示各种提示语,怎么办?
三、最终方案
1、返回认证失败
2、重定义响应头
- 步骤1:返回认证失败
if(o == null){
//token为null,返回错误信息,并且拒绝访问
responseError(servletResponse, HttpCodeEnum.UNAUTHORIZED.getCode(),"token失效了!");
return false;
}
- 步骤2:重定义响应头
JsonResult jsonResult = new JsonResult(code,errorMsg,null);
OutputStream os = httpServletResponse.getOutputStream();
os.write(new ObjectMapper().writeValueAsString(jsonResult).getBytes("UTF-8"));
os.flush();
os.close();