0

我的要求是打印自定义错误消息,但在响应正文中,它会给出通常的错误消息以及自定义错误消息,如下所示。时间戳部分不是必需的,但正在打印。请告诉我哪里出错了。

{ "status": "UNAUTHORIZED", "message": "Token_Expired" }{ "timestamp": "2021-04-17T19:50:27.748+00:00", "status": 401, "error": "Unauthorized", "message": "", "path": "/getEmployees" }

我的要求是在令牌过期时只获取响应正文 { "status": "UNAUTHORIZED", "message": "Token_Expired" }

异常建议类

` @RestControllerAdvice 公共类 ExceptionControllerAdvice 扩展 ResponseEntityExceptionHandler{

@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ErrorDTO processRuntimeException(Exception e) {
    return new ErrorDTO(HttpStatus.UNAUTHORIZED, "Token_Expired");
}

}`

过滤器类

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException, TokenExpiredException {
try{
  code.....
  code.....
}

catch(ExpiredJwtException ex){
        String newToken= request.getHeader("newToken");
        String requestURL = request.getRequestURL().toString();
        // allow for New Token creation if following conditions are true.
        if (newToken != null && newToken.equals("true") && requestURL.contains("newToken")) {
            allowFornewToken(ex, request);
        } 
        else{
            resolver.resolveException(request, response, null, ex);
            throw new TokenExpiredException();
        }
    } catch (BadCredentialsException ex) {
        request.setAttribute("exception", ex);
    } catch (Exception ex) {
        System.out.println(ex);
    }
    filterChain.doFilter(request, response);}

自定义消息的 TokenExpired 类

public class TokenExpiredException extends RuntimeException{

public TokenExpiredException() {
    super("TOKEN_EXPIRED");
}

}

4

0 回答 0