全局异常捕获不了这个方法里BaseException的自定义异常,该怎样捕获这个异常并返回Json数据?

来源:1-3 课程源码和文档资料

Sir丶666

2019-06-27

@Component
public class JwtAuthFilter extends OncePerRequestFilter {

private static final String BEARER = "Bearer ";

private static final Logger logger = LoggerFactory.getLogger(JwtAuthFilter.class);

@Autowired
private UserDetailsService jwtUserDetailsService;

@Autowired
private JwtTokenUtil jwtTokenUtil;

@Value ("${jwt.http.request.header}")
private String tokenHeader;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
                throws ServletException, IOException {

    final String requestTokenHeader = request.getHeader(this.tokenHeader);

    String username = null;
    String jwtToken = null;

    if((requestTokenHeader != null) && requestTokenHeader.startsWith(BEARER)) {
        jwtToken = requestTokenHeader.substring(7);
        try {
            username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            if((username != null) && (SecurityContextHolder.getContext()
                                                           .getAuthentication() == null)) {

                UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);


                if(jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                                    new UsernamePasswordAuthenticationToken(userDetails, null,
                                                                            userDetails.getAuthorities());
                    usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext()
                                         .setAuthentication(usernamePasswordAuthenticationToken);
                }
            }
        }
        catch (IllegalArgumentException e) {
            throw new BaseException(500,"从token中获取账号错误");
        }
        catch (ExpiredJwtException e) {
            throw new BaseException(500,"token已经过期了");
        }
        catch (Exception e) {
            logger.error(e.getLocalizedMessage());
        }
    }

    chain.doFilter(request, response);
}

}

写回答

1回答

廖师兄

2019-06-28

同学你是不是来错地方了,我这门课没教jwt啊

0
2
廖师兄
回复
Sir丶666
你这个是spring里filter,不是我课程里的zuulfilter, 你可以看看 https://blog.csdn.net/qq_19457117/article/details/88633225
2019-06-30
共2条回复

SpringCloud Finchley(M2+RELEASE+SR2)微服务实战

SpringCloud组件实现微服务,【已升级Finchley.Release】

5668 学习 · 2489 问题

查看课程