I use springmvc to create a calm api for the client, I have an interceptor to check accesstoken.
public class AccessTokenInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Authorize authorizeRequired = handlerMethod.getMethodAnnotation(Authorize.class); if (authorizeRequired != null) { String token = request.getHeader("accesstoken"); ValidateToken(token); } } return true; } protected long ValidateToken(String token) { AccessToken accessToken = TokenImpl.GetAccessToken(token); if (accessToken != null) { if (accessToken.getExpirationDate().compareTo(new Date()) > 0) { throw new TokenExpiredException(); } return accessToken.getUserId(); } else { throw new InvalidTokenException(); } }
And in my controller I use @ExceptionHandler to handle exceptions, the code for handling InvalidTokenException looks like
@ExceptionHandler(InvalidTokenException.class) public @ResponseBody Response handleInvalidTokenException(InvalidTokenException e) { Log.p.debug(e.getMessage()); Response rs = new Response(); rs.setErrorCode(ErrorCode.INVALID_TOKEN); return rs; }
But, unfortunately, the exception thrown by the preHandle method does not get into the exception handler defined in the controller.
Can someone give me a solution to handling exception? PS: My controller method creates both json and xml using the following code:
@RequestMapping(value = "login", method = RequestMethod.POST, produces = { "application/xml", "application/json" })
source share