spring boot@restcontrolladvice打印自定义错误消息和正常错误消息如何解决这个问题?

dphi5xsq  于 2021-07-14  发布在  Java
关注(0)|答案(0)|浏览(317)

我的要求是打印自定义错误消息,但在响应正文中,它给出了通常的错误消息以及自定义错误消息,如下所示。时间戳部分不是必需的,但正在打印它。请告诉我哪里出错了。 { "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" } 例外AdviceClass
`@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");
}

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题