【发布时间】:2018-07-13 01:01:40
【问题描述】:
我正在使用 Spring Boot 1.5.9 来开发我的应用程序。我需要实现 jwt 身份验证,并且我使用了 jjwt 库。以下代码来自我的自定义身份验证安全过滤器,它继承自 OncePerRequestFilter。在这里,我尝试从令牌中解析用户名,当用户名自动解析时经过 jwt 验证并检查令牌过期。我调试它并且它工作正常,所以我接下来想向客户端应用程序发送正确的消息,为什么身份验证失败。我想抛出一个 ExpiredJwtException 并使用我格式化输出的控制器建议来处理它。
这里是异常抛出:
try {
username = jwtTokenService.getUsername(authToken);
} catch (IllegalArgumentException e) {
logger.error("an error occured during getting username from token", e);
} catch (ExpiredJwtException e) {
logger.warn("the token is expired and not valid anymore", e);
throw new ExpiredJwtException(e.getHeader(), e.getClaims(), e.getMessage());
}
这是我的控制器建议,JwtException 是我抛出的 ExpiredJwtException 的基类,因此它应该可以工作。我也试过直接在ExceptionHandler中使用ExpiredJwtException,但效果不佳。接下来我想用同样的方式处理另一个异常。
@ControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(Exception.class)
public @ResponseBody
ResponseEntity<Map<String, Object>> handleException(Exception ex) {
Map<String, Object> errorInfo = new HashMap<>();
errorInfo.put("message", ex.getMessage());
errorInfo.put("status", HttpStatus.BAD_REQUEST);
errorInfo.put("status_code", HttpStatus.BAD_REQUEST.value());
return new ResponseEntity<>(errorInfo, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(JwtException.class)
//@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public @ResponseBody
ResponseEntity handleJwtException(JwtException ex) {
Map<String, Object> errorInfo = new HashMap<>();
errorInfo.put("message", ex.getLocalizedMessage());
errorInfo.put("status", HttpStatus.UNPROCESSABLE_ENTITY);
errorInfo.put("status_code", HttpStatus.UNPROCESSABLE_ENTITY.value());
return new ResponseEntity<>(errorInfo, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
我只想返回 4xx 状态的响应,但是当我的异常被抛出时,我总是得到 5xx 内部错误。你能告诉我我的代码有什么问题吗?感谢您的建议。
【问题讨论】:
-
是否调用了任何异常处理程序方法?
-
@Synch 我尝试了另一个异常,例如运行时,也没有处理任何事情
-
你能把你的第一个代码 sn-p 的类和方法贴出来吗?
标签: java spring spring-boot