package com.ycgis.macall.personalcenter.p.request;/*
 * 项目名：xayss
 * 作者：马超
 * 类目：HttpErrorHander.java
 * 包名：com.ruansee.sx.xayss.p.request.HttpErrorHander
 * 当前修改时间：2023年07月04日 16:52:58
 * 上次修改时间：2023年07月04日 16:52:58
 * Copyright©：2023 安徽软思信息技术有限公司
 * 功能描述：
 */

import com.google.gson.JsonParseException;
import com.rs.macall.androidx.basemodel.utils.LogUtils;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import retrofit2.HttpException;

public class HttpErrorHandler {
    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    /**
     * 统一处理Throwable
     * @param e e
     * @return msg
     */
    public static String requestHandle(Throwable e) {
        String msg;
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            switch (httpException.code()) {
                case UNAUTHORIZED:
                case FORBIDDEN:
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case GATEWAY_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                default:
                    msg = httpException.code()+"服务器错误";
                    break;
            }
        }  else if (e instanceof JsonParseException || e instanceof JSONException
                || e instanceof ParseException) {
            msg = "数据解析异常";
        } else if (e instanceof ConnectException || e instanceof SocketTimeoutException
                || e instanceof UnknownHostException) {
            msg = "连接失败，请检查网络";
        }  else if (e instanceof NumberFormatException){
            msg = "数字格式化异常";
        } else {
            msg = e.getMessage();
        }
        LogUtils.e("Request failure",msg);
        return msg;
    }
}
