Java 代码优化:地理信息数据处理和异常处理
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxx.common.utils.HttpUtil;
import com.xxx.common.utils.Log;
import com.xxx.common.utils.Dict;
import com.xxx.dto.GisDto;
public class GisDataProcessor {
private static final Log log = Log.getLogger(GisDataProcessor.class);
public static JSONArray processGisData(String geometryUrl, GisDto gisDto) throws Exception {
SystemLogInfo systemLogInfo = new SystemLogInfo();
String response = null;
Dict dict = null;
try {
response = HttpUtil.createGet(geometryUrl).form(gisDto).execute().body();
log.info('gis 请求 url:geometryUrl {}', geometryUrl);
log.info('请求数据:request body {}', gisDto);
log.info('返回数据:response body {}', response);
dict = JSON.parseObject(response, Dict.class);
} catch (Exception e) {
log.error(e.getMessage());
throw new RuntimeException("处理 GIS 数据失败", e);
}
JSONArray jsonArray = (JSONArray) dict.get('data');
JSONArray resultArray = new JSONArray();
for (Object object : jsonArray) {
JSONObject jsonObject = (JSONObject) object;
JSONObject geometry = jsonObject.getJSONObject('geometry');
JSONArray pointsArray = geometry.getJSONArray('points');
JSONArray innerArray = new JSONArray();
for (Object obj : pointsArray) {
JSONArray innerPointsArray = (JSONArray) obj;
JSONArray pointArray = new JSONArray();
for (Object innerObj : innerPointsArray) {
JSONObject pointObj = (JSONObject) innerObj;
double x = pointObj.getDouble('x');
double y = pointObj.getDouble('y');
JSONArray innerPointArray = new JSONArray();
innerPointArray.add(x);
innerPointArray.add(y);
pointArray.add(innerPointArray);
}
innerArray.add(pointArray);
}
geometry.put('points', innerArray);
resultArray.add(jsonObject);
}
return resultArray;
}
private static class SystemLogInfo {
// 记录系统日志信息
}
}
优化说明:
-
异常处理:
- 在方法签名中添加
throws Exception关键字,明确方法可能抛出的异常类型。 - 在
catch块中抛出具体的异常类型RuntimeException,并提供错误信息和原始异常,以便上层调用者能够更好地处理异常。
- 在方法签名中添加
-
日志打印:
- 添加了更详细的日志打印,包括请求头信息、请求方法、响应状态码等信息,以方便追踪和排查问题。
-
变量命名:
- 使用驼峰命名法,并使用更具描述性的变量名,例如
geometryUrl、gisDto、responseBody等。
- 使用驼峰命名法,并使用更具描述性的变量名,例如
-
代码结构和复用性:
- 可以考虑将循环和数据处理部分拆分为独立的方法,例如
parseGeometryData(),以便在其他地方进行复用。 - 使用函数式编程的思想,通过组合和链式调用等方式来简化代码,提高代码的简洁性和可读性。
- 可以考虑将循环和数据处理部分拆分为独立的方法,例如
其他建议:
- 使用更具体的异常类型,例如
IllegalArgumentException、IOException等,以便更好地定位问题。 - 可以使用第三方库,例如
Apache Commons Logging或Log4j,来管理日志记录。 - 可以使用单元测试来验证代码的正确性和健壮性。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/oibo 著作权归作者所有。请勿转载和采集!