需要抛自定义异常的地方

  1. @Autowired
  2. private HttpServletResponse response;
  3. public boolean verify(String token, String username, String secret) {
  4. try {
  5. Algorithm algorithm = Algorithm.HMAC256(secret);
  6. JWTVerifier verifier = JWT.require(algorithm)
  7. .withClaim("username", username)
  8. .build();
  9. DecodedJWT jwt = verifier.verify(token);
  10. return true;
  11. } catch (Exception exception) {
  12. //这里在catch直接转发
  13. try {
  14. response.sendRedirect("/402");
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. }
  18. return false;
  19. }
  20. }

然后controller层

  1. @RestController
  2. public class TestController {
  3. @GetMapping("/402")
  4. public ResponseBean a402() {
  5. return new ResponseBean(999, "token校验失败了.请重新登录", null);
  6. }

注意是get请求,路径别写错了,不然不好使.这样就可以避开源码里面的上层try catch 捕获了