使用Java异常的内部REST API的用户错误? [英] Use Java exceptions internally for REST API user errors?

查看:219
本文介绍了使用Java异常的内部REST API的用户错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个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值电影URL参数撞车,还是阿凡达。首先,我们检查,看它是否有一个有效的价值。

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?


  • 从内部的方法之一,并在主API调用的方法检查返回null空

  • 从内部方法抛出一个异常,并赶在主API方法例外

我认为这将使我们的code更具可读性和优雅的使用异常。但是,我们不愿意因为我们会被扔的潜在用户,因为API输入错误的许多例外,我们的code可能是完美的。这似乎并不正确使用异常。如果有沉重的性能损失有例外,这将使感与堆栈跟踪需要被收集起来,等等,那么我们花费不必要的资源时,我们需要做的是告诉用户该参数是错误的。

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方法,所以我们不会propogating的例外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的客户端不应该被接受为空或异常。他们应该得到,让他们发生了什么事情不暴露这些细节的想法的错误消息。 对不起,我们找不到那部电影还是空?与第一走,手了。

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的用户错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆