Spring Boot-将Exception对象从ResponseEntityExceptionHandler传递给HandlerInterceptor?

我正在研究Spring Boot Example,并实现了GlobalExceptionHandler,并尝试以JSON打印所有错误消息-这是我的自定义方法。

另外,我有ExceptionHandler捕获了所有异常。但是有什么方法可以将异常对象从ResponseEntityExceptionHandler传递到HandlerInterceptor

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,Object handler,ModelAndView modelAndView) throws Exception {

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

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

ExceptionHandler:

@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);
    }

    .........
    ..........
    .........
}
xuyuqun 回答:Spring Boot-将Exception对象从ResponseEntityExceptionHandler传递给HandlerInterceptor?

您可以将其设置为ExceptionHandler类中的请求属性(如果需要它,只是为了确保您要打印日志,则可以通过布尔参数以不加载您的请求对象,而不是传递Exception对象)

request.setAttribute("exception",e);

并在您的HandlerInterceptor中将其用作

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

您可以使用WebMvcConfigurerAdapter

配置拦截器

17.15.3 Configuring Interceptors

  

您可以将HandlerInterceptors或WebRequestInterceptors配置为应用于所有传入请求或限制为特定的URL路径模式。

在Java中注册拦截器的示例:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

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

      }

  }
本文链接:https://www.f2er.com/3151866.html

大家都在问