Cloud Endpoints中UnauthorizedException与OAuthRequestException有什么区别?

时间:2014-08-13 15:41:53

标签: java google-app-engine google-cloud-endpoints

在Cloud Endpoints中,我了解在执行OAuth时,我需要检查user == null是否确定用户是否已通过身份验证。在用户为null的情况下,我应该抛出异常。在Google Cloud Endpoints示例代码段中,我看到了两种不同的例外情况。

OAuth documentation for cloud endpoints说要抛出OAuthRequestException。但是,我已经看到其他代码库(包括Udacity Course)抛出UnauthorizedException

我注意到OAuthRequestException没有从com.google.api.server.spi.ServiceException扩展,所以我认为UnauthorizedException是正确的选择吗?

我应该使用哪一个?

1 个答案:

答案 0 :(得分:0)

我会坚持UnauthorizedException' since it extends from the ServiceException`类。根据{{​​3}}和API最佳实践的文档,建议以一种方式映射异常,以便抛出正确的HTTP状态代码。

因此,在UnauthorizedException的情况下,抛出HTTP 401。

这是我通常在我的代码中执行的操作,我相信(以及您可以尝试的!)您将看到标准捕获所有HTTP错误代码被抛出,以防您抛出类似OAuthRequestException的异常不扩展ServiceException(HTTP 503或HTTP 500)