每当应用中发生 401 错误时,我的应用就会崩溃。 我创建了一个自定义错误处理程序,但我不确定如何让应用程序使用此错误处理程序,以便应用程序正常停止,而不会闪烁用户"不幸的是,应用程序已停止"。
这是我的代码:
... new RestAdapter.Builder()...setErrorHandler(getErrorHandler()).build();
public ErrorHandler getErrorHandler() {
return new ErrorHandler() {
@Override
public Throwable handleError(RetrofitError cause) {
Response r = cause.getResponse();
if (r != null && r.getStatus() == 401) {
Log.e(TAG, "user not authorized:" + cause.toString());
} else {
Log.e(TAG, "regular exception thrown for CloudManager");
}
return cause;
}
};
正如你可以用javadoc检查的那样,当你想把RetrofitError
包装成CustomError
异常时,会使用错误处理程序。它不会为你捕捉异常。
class MyErrorHandler implements ErrorHandler {
@Override public Throwable handleError(RetrofitError cause) {
Response r = cause.getResponse();
if (r != null && r.getStatus() == 401) {
return new UnauthorizedException(cause);
}
return cause;
}
}
为了防止应用程序崩溃,您必须更早地捕获错误。
@GET("/users/{user}/repos")
List<Repo> listRepos(@Path("user") String user);
try {
List<Repo> repos = retrofit.listRepos("octocat");
} catch (RetrofitError error) {
// TODO: handle error
}