背景
解决思路
关键代码
@RestControllerAdvice @Slf4j public class GlobalExceptionHandler { /** *业务异常 */ @ExceptionHandler(BusinessException.class) public RetResult businessExceptionHandler(HttpServletRequest request, BusinessException e){ if(Objects.nonNull(request)){ StringBuffer requestUrlBuffer = request.getRequestURL(); String method = request.getMethod(); String requestUrl = Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString(); log.info("BusinessException:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e); } return ResultUtil.error(e.getCode(), e.getMessage()); } /** *参数异常 */ @ExceptionHandler(ParamException.class) public RetResult paramExceptionHandler(HttpServletRequest request, ParamException e) { if (Objects.nonNull(request)) { StringBuffer requestUrlBuffer = request.getRequestURL(); String method = request.getMethod(); String requestUrl = Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString(); log.info("ParamException:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e); } return ResultUtil.error(e.getCode(), e.getMessage()); } /** *数据库异常 */ @ExceptionHandler(DataBaseException.class) public RetResult databseExceptionHandler(HttpServletRequest request, DataBaseException e) { if (Objects.nonNull(request)) { StringBuffer requestUrlBuffer = request.getRequestURL(); String method = request.getMethod(); String requestUrl = Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString(); log.info("DatabseExceptionHandler{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e); } return ResultUtil.error(e.getCode(), e.getMessage()); } @ExceptionHandler(RuntimeException.class) public RetResult runtimeExceptionHandler(HttpServletRequest request, RuntimeException e){ if(Objects.nonNull(request)){ StringBuffer requestUrlBuffer = request.getRequestURL(); String method = request.getMethod(); String requestUrl = Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString(); log.error("RuntimeException:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e); } return ResultUtil.error(EnumResultCode.UN_KNOW_ERROR.getCode(), e.getMessage()); } @ExceptionHandler(Exception.class) public RetResult exceptionHandler(HttpServletRequest request, Exception e){ if(Objects.nonNull(request)){ StringBuffer requestUrlBuffer = request.getRequestURL(); String method = request.getMethod(); String requestUrl = Objects.isNull(requestUrlBuffer) ? request.getRequestURI() : requestUrlBuffer.toString(); log.error("Exception:{}, \n请求URL: [{}], \n请求方式: [{}]\n", e.getMessage(), requestUrl, method, e); } return ResultUtil.error(EnumResultCode.SYSTEM_ERROR.getCode(), e.getMessage()); } }
代码下载