我正在研究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);
}
.........
..........
.........
}