- 线上bug异常捕捉
- 背景:上线的时候发现一个bug,参数类型定义是一个Long型,但是前端传递过来的参数是一个undefined,导致解析失败。但是查看日志打印只显示类型转换错误(MethodArgumentTypeMismatchException),也不清楚调的是哪个接口.于是调整了一下日志捕捉代码。
@ExceptionHandler(MissingServletRequestParameterException.class) public ResponseData<Object> paramErrorHandler(MissingServletRequestParameterException e, HttpServletRequest request) { log(e, request); return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), e.getMessage()); } @ExceptionHandler(MethodArgumentTypeMismatchException.class) public ResponseData<Object> mismatchErrorHandler(MethodArgumentTypeMismatchException e, HttpServletRequest request) { log.error("方法:{},字段:{},参数:{},错误信息:{}", e.getParameter().getMethod(), e.getName(), e.getValue(), e.getMessage()); return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), e.getMessage()); } @ExceptionHandler(BusinessException.class) public ResponseData<Object> handler(BusinessException e) { log.error("业务异常:{}", (Object) e); return ResponseData.fail(e.getCode() == null ? ResponseCode.INTERNAL_ERROR.getCode() : e.getCode(), e.getMsg()); } @ExceptionHandler(ParamException.class) public ResponseData<Object> handler(ParamException e) { log.error("参数异常:{}", (Object) e); return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), e.getMsg()); } @ExceptionHandler public ResponseData<Object> handler(Exception e, HttpServletRequest request) { // Exception 打印最全信息 log(e, request); return ResponseData.fail(ResponseCode.INTERNAL_ERROR.getCode(), IcebergConstant.ERROR_MSG_EXCEPTION); } private void log(Exception e, HttpServletRequest request) { log.error("ipAddress->{}", getIpAddress(request)); log.error("url->{}", request.getRequestURL()); log.error("error->{}", (Object) e); } public String getIpAddress(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); String unknown = "unknown"; if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; }