Search in sources :

Example 1 with BaseResponse

use of com.boredream.bdcodehelper.lean.entity.BaseResponse in project bdcodehelper by boredream.

the class LcErrorConstants method parseHttpErrorInfo.

/**
 * 解析服务器错误信息
 */
public static String parseHttpErrorInfo(Throwable throwable) {
    String errorInfo = throwable.getMessage();
    if (throwable instanceof HttpException) {
        // 如果是Retrofit的Http错误,则转换类型,获取信息
        HttpException exception = (HttpException) throwable;
        ResponseBody responseBody = exception.response().errorBody();
        MediaType type = responseBody.contentType();
        // 如果是application/json类型数据,则解析返回内容
        if (type != null && type.type().equals("application") && type.subtype().equals("json")) {
            try {
                // 这里的返回内容是Bmob/AVOS/Parse等RestFul API文档中的错误代码和错误信息对象
                BaseResponse errorResponse = new Gson().fromJson(responseBody.string(), BaseResponse.class);
                errorInfo = getLocalErrorInfo(errorResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else if (throwable instanceof LcErrorResponse) {
        LcErrorResponse lce = (LcErrorResponse) throwable;
        errorInfo = getLocalErrorInfo(lce.getError());
    } else {
        if (throwable instanceof UnknownHostException) {
            errorInfo = "无法连接到服务器";
        }
    }
    return errorInfo;
}
Also used : BaseResponse(com.boredream.bdcodehelper.lean.entity.BaseResponse) UnknownHostException(java.net.UnknownHostException) MediaType(okhttp3.MediaType) Gson(com.google.gson.Gson) HttpException(retrofit2.HttpException) LcErrorResponse(com.boredream.bdcodehelper.lean.entity.LcErrorResponse) HttpException(retrofit2.HttpException) UnknownHostException(java.net.UnknownHostException) ResponseBody(okhttp3.ResponseBody)

Aggregations

BaseResponse (com.boredream.bdcodehelper.lean.entity.BaseResponse)1 LcErrorResponse (com.boredream.bdcodehelper.lean.entity.LcErrorResponse)1 Gson (com.google.gson.Gson)1 UnknownHostException (java.net.UnknownHostException)1 MediaType (okhttp3.MediaType)1 ResponseBody (okhttp3.ResponseBody)1 HttpException (retrofit2.HttpException)1