繁体   English   中英

Spring Boot @ExceptionHandler没有捕获相关异常

[英]Spring boot @ExceptionHandler isn't catching relevant exception

我正在使用Spring Boot构建API。 我已经设置了一个身份验证过滤器,以从请求标头中获取令牌并对其进行身份验证。 如果找不到使用令牌的用户,则抛出InvalidWSUserException。

我创建了一个用于容纳多个@ExceptionHandlers的类,以便可以捕获InvalidWSUserException并使用JSON字符串进行响应,以通知发出请求的客户端其请求中的令牌无效。

我曾经在另一个项目上工作过,但似乎无法在新项目中使用它。

InvalidWSUserException为空,因为处理程序应该处理响应;

public class InvalidWSUserException extends RuntimeException {
}

我已经定义了处理程序类;

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(value=InvalidWSUserException.class)
    public ResponseEntity invalidWSUserException(InvalidWSUserException exception) {
        return new WSResponse().send(HttpStatus.UNAUTHORIZED, "Invalid token.");
    }

}

我在以前的项目中遇到了一个问题,在那个项目中,引发异常的类尚未由Spring通过Bean实例化,但是我检查了此类,而引发异常的类则由@实例化。自动装配注释。

我正在努力理解为什么@ExceptionHandler没有按我的预期去做。

确认一下,我在浏览器中看到的输出是错误500 json响应; 应该是@ExceptionHandler中的EntityResponse

{
  "timestamp": 1470833849289,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "digital.sheppard.exceptions.InvalidWSUserException",
  "message": "No message available",
  "path": "/api/product"
}

我正在使用用于Java库的JSON Web令牌 ,并且如上所述,在身份验证服务中出现了相同的错误。 我已经尝试使用@ControllerAdvice,但是没有解决方案。

经过长时间的研究,我找到了解决方案。 您必须实现JwtFilter ,而不是启动异常,而必须修改HttpServletResponse值以添加以下内容:

if (authHeader == null || !authHeader.startsWith("Bearer ")) {
   //throw new UnauthorizedErrorException(UnauthorizedErrorException.ErrorCodes.INVALID_TOKEN);

   response.addHeader("Content-Type", "application/json");
   response.getWriter().print(getErrorJson());    
   response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

   return;
}

final String token = authHeader.substring(7);

try {
   final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
   request.setAttribute("claims", claims);
} catch (final SignatureException e) {
   //throw new UnauthorizedErrorException(UnauthorizedErrorException.ErrorCodes.INVALID_TOKEN);

   response.addHeader("Content-Type", "application/json");
   response.getWriter().print(getErrorJson());           
   response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

   return;
}

chain.doFilter(req, res);

如您所见,我已经注释了异常启动,并为响应标头覆盖对其进行了更改。 getErrorJson()返回一个JSON值作为字符串(或者您只能将字符串作为正文)。

我希望这对您有用。

PD:我已按照以下说明进行身份验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM