微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在使用springmvc为客户端创建restful 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"
})
最佳答案
使用其他方法解决,捕获异常并转发到另一个控制器.

try
{
    Validatetoken(token);
} catch (InvalidTokenException ex)
{
    request.getRequestdispatcher("/api/error/invalidtoken").forward(request,response);
    return false;
} catch (TokenExpiredException ex)
{
    request.getRequestdispatcher("/api/error/tokenexpired").forward(request,response);
    return false;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐