java 我应该捕获 EmptyResultDataAccessException 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16406349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:51:45  来源:igfitidea点击:

Should I Catch EmptyResultDataAccessException?

javaspringspring-jdbc

提问by EdgeCase

I have a SQL statement that I expect will return one row, because I am passing the primary key. So my choices are to

我有一个 SQL 语句,我希望它返回一行,因为我正在传递主键。所以我的选择是

  1. Wrap the queryForObjectin a try/catch, catching EmptyResultDataAccessException, and returning null
  2. Change the call to queryForList, and unwrap the List and (hopefully) return the 1st element, or null.
  1. queryForObject 包裹在 try/catch 中,捕获 EmptyResultDataAccessException,并返回 null
  2. 更改对queryForList的调用,并解开 List 并(希望)返回第一个元素,或 null。

I read somewhere the cathing an EmptyResultDataAccessException, since it extends runtime exception, is a bad practice.

我在某处读到了一个 EmptyResultDataAccessException,因为它扩展了运行时异常,这是一种不好的做法。

But I can't see anything wrong with it.

但我看不出有什么问题。

I would be interested in hearing opinions

我有兴趣听取意见

采纳答案by Manuel Quinones

Most of the time I have run into this(mvc/ws) I let the exception be thrown but handle the exception in an exception resolver. The problem with returning null is that an application is depending on it and further down the road and you would have to do a null check later rather than at the time it is expected to be there. This can cause problems because not all developers may be doing the null check when required and then you could run into npe later. Depending on what type of application you are writing there are several ways to catch and handle the exception using an exception resolver. By using an exception resolver you can handle each exception differently and provide feedback to the user.

大多数时候我都遇到过这个(mvc/ws),我让异常被抛出,但在异常解析器中处理异常。返回 null 的问题在于应用程序依赖于它并且在更远的道路上进行,并且您必须稍后进行 null 检查,而不是在预期出现时进行。这可能会导致问题,因为并非所有开发人员都可能在需要时进行空检查,然后您可能会在以后遇到 npe。根据您正在编写的应用程序类型,有多种使用异常解析器捕获和处理异常的方法。通过使用异常解析器,您可以以不同方式处理每个异常并向用户提供反馈。

Here is one way to do it using spring mvc. This way you can put a general message to a user if the object with the primary key does not exist. http://www.mkyong.com/spring-mvc/spring-mvc-exception-handling-example/

这是使用 spring mvc 的一种方法。如果具有主键的对象不存在,您可以通过这种方式向用户发送一般消息。 http://www.mkyong.com/spring-mvc/spring-mvc-exception-handling-example/

回答by GriffeyDog

I think it's perfectly acceptable to catch that exception. It's the only Spring exception I catch that I can recall, but I have valid use cases for trying to find a record that is potentially not in existence.

我认为捕获该异常是完全可以接受的。这是我能记得的唯一捕获的 Spring 异常,但我有有效的用例来尝试查找可能不存在的记录。