空指针产生的原因
- 没有对new出来的对象进行实例化
- 去数据库查一个空的对象
- 对象为null的情况下去调用该对象所拥有的方法或成员变量
- 对null对象进行遍历(业务中遇到)
排错思路
首先是看报错的日志
通过日志定位到具体的controller的具体行数,报错为第一行,因此怀疑是遍历过程中出的问题
for (Domain domain : schoolList) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", CodecUtils.encode(domain.getId()));
map.put("name", domain.getName());
map.put("orgId", domain.getOrgId());
enschoolList.add(map);
}
现在要拿取schoolList就要进入到service方法中去
service方法分析,大致代码结构如下
public List<Domain> retrieve() {
List<Domain> result = new ArrayList<Domain>();
Domain domain = null;
JSONObject obj = null;
try {
String url =
address + "请求路径" + domainName + getUrl();
ClientDto clientDto = OkHttpClient.doGet(url, StringUtils.EMPTY);
if (null == clientDto || StringUtils.isEmpty(clientDto.getCode())
|| !clientDto.getCode().equals(ClientCodeType.SUCCESS)) {
return null;
}
JSONArray jsonObject = (JSONArray) clientDto.getValue();
for (int i = 0; i < jsonObject.size(); i++) {
obj = (JSONObject) jsonObject.get(i);
domain = new Domain();
domain.setId(Integer.valueOf(obj.getString("domainId")));
domain.setName(obj.getString("domainName"));
result.add(domain);
}
return result;
}
catch (Exception e) {
if (logger.isErrorEnabled()) {
System.out.println("异常处理");
}
}
return null; //return result是否是有必要
}
分析如下
service层通过http去调取另外一个服务的地址进行数据的查询,此时如果服务挂了,就会执行if里ClinetDto的相关判断从而去返回null,这时controller层里的schoolList接收的就是null,对其遍历就会报空指针问题
总结
这个bug产生的原因就是在service层通过http协议请求去调服务失败后给了null,此时应该设置一个code值标记一下,返回给controller层让controller知道,随意返回null值很容易报空指针错误,编码规范。