加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:49:47 所属栏目:大数据 来源:网络整理
导读:我正在使用springmvc为客户端创建restful api,我有一个用于检查accesstoken的拦截器. public class AccessTokenInterceptor extends HandlerInterceptorAdapter{ @Overridepublic boolean preHandle(HttpServletRequest request,HttpServletResponse respons

我正在使用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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读