如何在弹簧拦截器中使用@ExceptionHandler?
2022-09-04 03:44:40
我正在使用springmvc为客户端创建宁静的api,我有一个用于检查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();
}
}
在我的控制器中,我使用@ExceptionHandler来处理异常,处理InvalidTokenException的代码看起来像
@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;
}
但不幸的是,在 preHandle 方法中引发的异常没有被控制器中定义的异常处理程序捕获。
任何人都可以给我一个处理异常的解决方案吗?PS:我的控制器方法使用以下代码生成json和xml:
@RequestMapping(value = "login", method = RequestMethod.POST, produces =
{
"application/xml", "application/json"
})