问题描述
我们有一个很好用的 REST API.我们正在重构并决定如何在内部处理 API 用户的错误.
We have a REST API that works great. We're refactoring and deciding how to internally handle errors by the users of our API.
例如,用户需要指定电影"网址参数,该参数应取1984"、崩溃"或阿凡达"的值.首先,我们检查它是否具有有效值.
For example the user needs to specify the "movie" url parameter which should take the value of "1984", "Crash", or "Avatar". First we check to see if it has a valid value.
如果电影参数无效,最好的方法是什么?
What would be the best approach if the movie parameter is invalid?
- 从内部方法之一返回 null 并检查主 API 调用方法中的 null
- 从内部方法抛出异常并在主 API 方法中捕获异常
我认为使用异常会使我们的代码更具可读性和优雅性.然而,我们不情愿,因为我们可能会因为用户 API 输入错误而抛出许多异常,我们的代码可能是完美的.这似乎不是异常的正确使用.如果异常会导致严重的性能损失,这对需要收集堆栈跟踪等有意义,那么当我们需要做的只是告诉用户参数错误时,我们就不必要地消耗了资源.
I think it would make our code more readable and elegant to use exceptions. However, we're reluctant because we'd be potentially throwing many exceptions because of user API input errors, our code could be perfect. This doesn't seem to be the proper use of exceptions. If there are heavy performance penalties with exceptions, which would make sense with stack traces needing to be collected, etc., then we're unnecessarily spending resources when all we need to do is tell the user the parameter is wrong.
这些是 REST API 方法,因此我们不会向 API 的用户传播异常,即使可能,我们也不想这样做.
These are REST API methods, so we're not propogating the exceptions to the users of the API, nor would we want to even if possible.
那么这里的最佳实践是什么?使用丑陋的空值还是使用java的异常机制?
So what's the best practice here? Use ugly nulls or use java's exception mechanism?
推荐答案
都没有.
关键在于,传递一个错误的参数并不是一种特殊的情况.异常情况下会抛出异常.(这是这里不使用它们的原因,而不是性能.)
The key is that passing a bad parameter isn't that exceptional a condition. Exceptions are thrown for exceptional circumstances. (That's the reason to not use them here, not the performance.)
您应该使用类似 Spring 的 DataValidation API 来绑定传入的参数.
You should be using something like Spring's DataValidation API for binding parameters that are passed in.
REST API 的客户端不应收到 null 或异常.他们应该收到一条错误消息,让他们在不暴露这些细节的情况下了解正在发生的事情.抱歉,我们找不到那部电影"或 null?用第一个,放下手.
A client of a REST API should not be receiving null or exceptions. They should get an error message that gives them an idea of what's going on without exposing those details. "Sorry, we couldn't find that movie" or null? Go with the first, hands down.
这篇关于在内部使用 Java 异常处理 REST API 用户错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!