【问题标题】:Send an error to appengine endpoint client向 appengine 端点客户端发送错误
【发布时间】:2016-02-18 02:53:48
【问题描述】:

在我的 GAE 端点中,在我的用户注册 API 方法中,我检查是否已经存在具有给定用户名的用户。如果用户已经存在,我需要向端点客户端发送错误。

目前我从端点抛出一个exception,如下所示。

User user = ofy().load().key(Key.create(User.class, username)).now();
if (user != null) {
    throw new BadRequestException("Username already exists");
}

然后在端点客户端中,我捕获了如下异常。

try {
    gaeEndpoint.registerUser(mEmail, mPassword).execute();
} catch (HttpResponseException e) {
    mErrorMessage = e.getContent();
} catch (IOException e) {
    mErrorMessage = "Failed to communicate with server. Please check your internet connection.";
}

当端点抛出 BadRequestException 时,客户端会得到 HttpResponseException ee.getContent() 包含一个 json 字符串,其中包含从端点发送的错误消息字符串。我需要解析 json 以获取从服务器发送的实际错误消息。

尽管这可行,但我觉得应该有更好的方法从端点向客户端发送错误消息。那么,有没有人知道更好(或推荐)的方法?

【问题讨论】:

  • 我觉得没问题。您的HttpResponseException 不仅包含内容部分。它应该包含一个 statusCode,它应该比内容更容易在代码中处理,因为if(statusCode == 400){Whoopsie...} 比解析响应和使用它更容易。

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


【解决方案1】:

我认为你做的一切都是对的。

HTTP 旨在向用户发送带有 4xx 代码和有意义内容的响应。它可以是浏览器的 HTML、api 客户端的 JSON 或任何可以为客户端提供上下文的东西。

如果您担心使用异常,那也没关系。当然,您可以使用手动设置的状态代码准备响应,但这不会改变任何东西,它只是更多的代码。在这种情况下,当您使用异常时,您也不太可能创建错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-27
    • 2018-03-08
    • 2019-01-26
    • 2017-02-14
    • 2021-10-16
    • 2015-01-08
    • 2014-08-10
    • 2018-07-18
    相关资源
    最近更新 更多