gpt4 book ai didi

java - 在 REST API 中使用受检异常与未受检异常

转载 作者:行者123 更新时间:2023-11-30 06:49:21 24 4
gpt4 key购买 nike

根据[1],

"When deciding on checked exceptions vs. unchecked exceptions, ask yourself, What action can the client code take when the exception occurs?. If the Client code cannot do anything, Make it an unchecked exception. And if the Client code will take some useful recovery action based on information in the exception, make it a checked exception."

我明白了总体思路。但是,我的困惑是,“客户端代码”是什么意思。假设我正在编写一个 REST API,它有一个调用实际后端层的服务层(我也在其中进行验证)。

API User --calls--> { |Service Layer| --internally calls--> |Backend Layer| }
  1. 那么 API 用户也被视为“客户端代码”?
  2. 对于请求验证,我应该抛出已检查异常还是未检查异常?
  3. 避免使用受检异常的最佳做法是什么?
  4. 是否可以在验证中抛出未经检查的异常,让它冒泡,然后在服务层捕获它并将其包装在自定义异常中? (并使用 JAX-RS ExceptionMapper [3] 向 API 用户展示)

引用资料:

[1] http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html

[2] http://archive.oreilly.com/pub/post/avoiding_checked_exceptions.html

[3] https://docs.oracle.com/javaee/6/api/javax/ws/rs/ext/ExceptionMapper.html

最佳答案

Q1: So the API User is also considered as a "Client code"?

是的。

Q2: For request validations, should I throw Checked or Unchecked Exceptions?

引用您问题中的建议:“如果客户端代码无法执行任何操作,则将其设置为未经检查的异常。如果客户端代码将根据异常中的信息采取一些有用的恢复操作,则将其设置为检查异常。”

Q3: Is the best practice to avoid using checked exceptions?

没有。

Q4: Is is ok to throw unchecked exceptions in validations, and let it bubble up, and catch and wrap it with in a custom exception at the Service Layer? (and use JAX-RS ExceptionMapper [3] to show that to the API user)

“可以吗”取决于你问的是谁。它还取决于它是否适合您。

如果您将所有内容都变成未经检查的异常,那么编译器无法帮助您检查应该处理的异常是否已处理。

在您的模型中,必须有一些东西将需要由客户端 API 的调用者处理的错误与不需要的错误区分开来。可以做到……但是您更依赖于 API 客户端程序员来了解什么是正确的事情。如果没有检查异常,他/她可以简单地忽略异常……直到它们导致系统测试失败、生产失败。

你们的程序员有多好?你的文档有多好?您的质量控制/测试制度有多好?

关于java - 在 REST API 中使用受检异常与未受检异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42882257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com