簡體   English   中英

Spring 引導 - 將異常 object 從 ResponseEntityExceptionHandler 傳遞到 HandlerInterceptor?

[英]Spring Boot - Pass Exception object from ResponseEntityExceptionHandler to HandlerInterceptor?

我正在研究 Spring 引導示例並實現GlobalExceptionHandler並嘗試在 JSON 中打印所有錯誤消息 - 這是我的自定義方法。

另外,我有ExceptionHandler在那里我捕獲了所有異常。 但是有沒有辦法將異常 object 從ResponseEntityExceptionHandler傳遞給HandlerInterceptor

處理程序攔截器:

@Slf4j
public class GlobalExceptionHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        ............
        .............
        ..............
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

        ServletRequestAttributes attributes = (ServletRequestAttributes) request.getAttribute(REQUEST_ATTRIBUTES);
        ServletRequestAttributes threadAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();    
        ............
        .............
        ..............
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        if(ex != null) {
            printJsonReq(request, response);
        }
    }
}

異常處理程序:

@ControllerAdvice
@Slf4j
public class ExceptionHandler extends ResponseEntityExceptionHandler{

    @ExceptionHandler({ResponseStatusException.class})
    protected ResponseEntity<Object> handleResStatusException(Exception e, WebRequest request, HttpServletRequest httpRequest) {
        ResponseStatusException be = (ResponseStatusException) e;

        ErrorResource error = ErrorResource.builder().code(AppConst.BAD_REQUEST)
                .message(ExceptionUtils.getDetails(e.getCause())).build();

        return handleExceptionInternal(e, error, getHeaders(), HttpStatus.BAD_REQUEST, request);
    }

    .........
    ..........
    .........
}

您可以將其設置為ExceptionHandler class 中的請求屬性(如果您需要它只是為了確保要打印日志,那么您可以傳遞 boolean 參數而不是傳遞異常 object 參數來加載您的對象)

request.setAttribute("exception", e);

並在您的 HandlerInterceptor 中使用它作為

if(ex != null || request.getAttribute("exception") != null) {
   printJsonReq(request, response);
}

您可以使用WebMvcConfigurerAdapter配置攔截器

17.15.3 配置攔截器

您可以將 HandlerInterceptors 或 WebRequestInterceptors 配置為應用於所有傳入請求或限制為特定的 URL 路徑模式。

Java中注冊攔截器的示例:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
     registry.addInterceptor(new GlobalExceptionHandler());

      }

  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM