【发布时间】: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 e 和 e.getContent() 包含一个 json 字符串,其中包含从端点发送的错误消息字符串。我需要解析 json 以获取从服务器发送的实际错误消息。
尽管这可行,但我觉得应该有更好的方法从端点向客户端发送错误消息。那么,有没有人知道更好(或推荐)的方法?
【问题讨论】:
-
我觉得没问题。您的
HttpResponseException不仅包含内容部分。它应该包含一个 statusCode,它应该比内容更容易在代码中处理,因为if(statusCode == 400){Whoopsie...}比解析响应和使用它更容易。
标签: java google-app-engine google-cloud-endpoints