代码之家  ›  专栏  ›  技术社区  ›  Kirill Zotov

修改处理服务器错误

  •  0
  • Kirill Zotov  · 技术社区  · 10 年前

    只是绑改装,它是伟大的。不想发明新的东西,所以有没有办法处理 failure() . 或者唯一的方法是检查所有状态,例如显示对话框?

     @Override
      public void failure(RetrofitError error) {
    
      }
    
    2 回复  |  直到 10 年前
        1
  •  1
  •   Smashing    10 年前

    如果您构建了retrofit适配器,您将看到它可以选择包含自定义错误处理程序。使用的方法是 .setErrorHandler(errorHandler);

    因此,您可以创建以下类,并以上述方式将其附加到改装生成器:

    public class ErrorUtil implements ErrorHandler {
    
    
        public ErrorUtil() {
    
        }
    
        public Throwable handleError(RetrofitError cause) {
            String errorDescription = null;
            Log.e("NON FATAL ERROR: ", cause.getLocalizedMessage());
    
            if (cause.getKind().equals(RetrofitError.Kind.NETWORK)) {
                if (!isNetworkAvailable()) {
                    errorDescription = ErrorConstants.ERROR_CONNECTION_OFFLINE;
                } else if (cause.getMessage().contains("Unable to resolve host") || cause.getMessage().contains("Invalid sequence") || cause.getMessage().contains("Illegal character") || cause.getMessage().contains("was not verified")) {
                    errorDescription = ErrorConstants.ERROR_UNABLE_TO_RESOLVE_HOST;
                } else if (cause.getLocalizedMessage().contains("timeout") || cause.getLocalizedMessage().contains("timed out") || cause.getLocalizedMessage().contains("failed to connect")) {
                    errorDescription = ErrorConstants.ERROR_CONNECTION_TIMEOUT;
                } else if (cause.getLocalizedMessage().equals("Connection closed by peer") || cause.getLocalizedMessage().equals("host == null") || cause.getLocalizedMessage().contains("CertPathValidatorException")) {
                    errorDescription = ErrorConstants.ERROR_UNABLE_TO_RESOLVE_HOST;
                } else {
                    errorDescription = ErrorConstants.ERROR_NETWORK;
                }
            } else if (cause.getKind().equals(RetrofitError.Kind.CONVERSION)) {
                errorDescription = ErrorConstants.ERROR_JSON_RESPONSE_CONVERSION;
            } else if (cause.getResponse() == null) {
                errorDescription = ErrorConstants.ERROR_NO_RESPONSE;
            } else {
                errorDescription = ErrorConstants.ERROR_UNKNOWN;
            }
            Log.d("ERRORUTILReturn", errorDescription);
            return new Exception(errorDescription);
        }
    

    很抱歉发布了一堵代码墙,但这是我们用来从改装错误处理程序中获取可读错误格式的解决方案。您可以编辑它以更好地匹配错误集。我们还将错误消息本地化到错误处理程序类中。

    然后,只需使用以下内容即可获得可读的错误格式,您可以将其显示给用户:

    @Override
      public void failure(RetrofitError error) {
    error.getLocalizedMessage();
      }
    
        2
  •  1
  •   Rohan    10 年前

    我在网上遇到了一个定制的错误处理程序(gist),它肯定会对您有所帮助。

    https://gist.github.com/benvium/66bf24e0de80d609dac0

    您可以通过实现ErrorHandler接口来创建自定义错误处理程序。然后,可以使用rest适配器生成器的setErrorHandler(自定义错误处理程序)方法在rest适配器上设置该值。