我有以下引发异常的方法:
@ApiMethod(name = "login")
public Profile getLogin(User user) throws UnauthorizedException {
if (user == null){
throw new UnauthorizedException("missing user");
}
...
}
如何在android客户端AsyncTask中捕获错误?
protected Profile doInBackground(Void... unused) {
Profile profile = null;
try {
profile = service.login().execute();
} catch (Exception e) {
Log.d("exception", e.getMessage(), e);
}
return profile;
}
上面没有捕捉到 UnauthorizedException。
最佳答案
异常发生在 App Engine 服务器上,而不是 Android 客户端上。然后,您必须想办法向客户端发送消息,告诉他发生了什么异常。
在 Cloud Endpoints 和其他 REST API 中,这是使用 HTTP 结果代码和 HTTP 结果消息完成的。
Cloud Endpoints 文档解释了 how to match a custom exception to an HTTP result code .但是,在您的情况下,您还可以使用提供的 com.google.api.server.spi.response.UnauthorizedException
。这将转换为 HTTP 401 代码,这是 HTTP 表示“未经授权”的一种方式。
我从未在 Android 上尝试过 Cloud Endpoints,但如果你检查异常类,你肯定会看到有一种方法可以获取 HTTP 错误代码。
关于java - Google Cloud Endpoints 自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20876028/