I am working on Spring Boot Example and implemented GlobalExceptionHandler
and trying to print all error messages in JSON - it's my custom method.
Also, I have ExceptionHandler
there I am catching all the Exception. But is there any way to pass the exception object from ResponseEntityExceptionHandler
to 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);
}
}
}
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);
}
.........
..........
.........
}