【发布时间】:2019-11-06 13:18:46
【问题描述】:
我正在研究 Spring Boot 示例并实现 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, 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);
}
.........
..........
.........
}
【问题讨论】:
标签: spring spring-boot exceptionhandler handlerinterceptor