OncePerRequestFilter我无法返回HttpServletResponse自定义错误

时间:2018-04-13 10:44:25

标签: spring httpresponse

我有OncePerRequestFilter:

public class ApiAuthenticationFilter extends OncePerRequestFilter {
...
@Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException {
    String token = request.getHeader("X-Authorization");
    if (StringUtils.isEmpty(token)) {
      //return custom exception
      return;
    }

    User user = userService.findUserByToken(token);
    if (user == null) {
      //return custom exception
      return;
    }

    AuthUser authUser = new AuthUser(token, user);
    SecurityContextHolder.getContext().setAuthentication(authUser);

    filterChain.doFilter(request, response);
  }

如何向客户端返回我的自定义异常?

我尝试了response.sendError(777, "Authorization token is invalid");

但是客户端收到状态为500的错误。我可以从HttpServletResponse发送onli CONSTANT错误:

response.sendError(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED, "Authorization token required");

但是这个HttpServletResponse没有所有代码。例如,我想发送666错误。

0 个答案:

没有答案