简体   繁体   English

用JDBC查询抛出异常

[英]Throwing exceptions with jdbc query

I have following repository method: 我有以下存储库方法:

@Override
public List<Item> getItemsByName(String name) {
    String sql = "SELECT * FROM ITEMS WHERE NAME = :name";
    Map<String, Object> params = new HashMap<>();
    params.put("name", name);
    return jdbcTemplate.query(sql, params, new ItemMapper());
}

Now I want to throw ItemsNotFoundException when user passed item name that not exists. 现在,当用户传递不存在的项目名称时,我想抛出ItemsNotFoundException。 How should I do it? 我该怎么办? Should I throw exception when query() method return empty list or is null: 当query()方法返回空列表或为null时,是否应该引发异常:

List<Item> items = jdbcTemplate.query(sql, params, new ItemMapper());
if (items == null || items.isEmpty()) {
    throw new ItemsNotFoundException();
}
return items;

Or should I throw this exception when I will get DataAccessException: 还是在我将获得DataAccessException时抛出此异常:

try {
    return jdbcTemplate.query(sql, params, new ItemMapper());
} catch (DataAccessException e) {
    throw new ItemNotFoundException();
}

Passing in a name that doesn't exist won't result in a DataAccessException , so that won't work. 传递不存在的名称不会导致DataAccessException ,因此将无法正常工作。 There's nothing exceptional about an empty result for a query. 查询为空的结果没有什么例外。

However why do you want to throw an exception if the results are empty? 但是,如果结果为空,为什么要引发异常? Is it an exceptional case for you (ie it's a bug that someone would search for a name that doesn't exist)? 对您来说,这是否是例外情况(例如,有人搜索不存在的名称是一个错误)? If so, it's a valid approach. 如果是这样,这是一种有效的方法。 In the general sense an empty list would probably be better. 一般而言,空列表可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM