java – 如何在Spring Interceptor中使用@ExceptionHandler?

前端之家收集整理的这篇文章主要介绍了java – 如何在Spring Interceptor中使用@ExceptionHandler?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用springmvc为客户端创建restful api,我有一个用于检查accesstoken的拦截器.

  1. public class AccessTokenInterceptor extends HandlerInterceptorAdapter
  2. {
  3. @Override
  4. public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception
  5. {
  6. if (handler instanceof HandlerMethod)
  7. {
  8. HandlerMethod handlerMethod = (HandlerMethod) handler;
  9. Authorize authorizerequired = handlerMethod.getMethodAnnotation(Authorize.class);
  10. if (authorizerequired != null)
  11. {
  12. String token = request.getHeader("accesstoken");
  13. ValidateToken(token);
  14. }
  15. }
  16. return true;
  17. }
  18. protected long ValidateToken(String token)
  19. {
  20. AccessToken accessToken = TokenImpl.GetAccessToken(token);
  21. if (accessToken != null)
  22. {
  23. if (accessToken.getExpirationDate().compareTo(new Date()) > 0)
  24. {
  25. throw new TokenExpiredException();
  26. }
  27. return accessToken.getUserId();
  28. }
  29. else
  30. {
  31. throw new InvalidTokenException();
  32. }
  33. }

在我的控制器中,我使用@ExceptionHandler来处理异常,处理InvalidTokenException的代码看起来像

  1. @ExceptionHandler(InvalidTokenException.class)
  2. public @ResponseBody
  3. Response handleInvalidTokenException(InvalidTokenException e)
  4. {
  5. Log.p.debug(e.getMessage());
  6. Response rs = new Response();
  7. rs.setErrorCode(ErrorCode.INVALID_TOKEN);
  8. return rs;
  9. }

但不幸的是,preHandle方法抛出的异常并未被控制器中定义的异常处理程序捕获.

任何人都可以给我一个处理异常的解决方案吗?
PS:我的控制器方法使用以下代码生成json和xml:

  1. @RequestMapping(value = "login",method = RequestMethod.POST,produces =
  2. {
  3. "application/xml","application/json"
  4. })
最佳答案
使用其他方法解决,捕获异常并转发到另一个控制器.

  1. try
  2. {
  3. ValidateToken(token);
  4. } catch (InvalidTokenException ex)
  5. {
  6. request.getRequestDispatcher("/api/error/invalidtoken").forward(request,response);
  7. return false;
  8. } catch (TokenExpiredException ex)
  9. {
  10. request.getRequestDispatcher("/api/error/tokenexpired").forward(request,response);
  11. return false;
  12. }

猜你在找的Spring相关文章