안드로이드

Retrofit2 Callback Custom 레트로핏2 콜백 커스텀

알통몬_ 2021. 5. 14. 10:39
반응형
class ReformCallback<T>(var application: Apps, var listener : ResponseListener<T>): Callback<T> {

    interface ResponseListener<T> {
        fun successResponse(response: T)
        fun errorResponse(code: Int)
    }

    override fun onResponse(call: Call<T>, response: Response<T>) {
        Log.e("ReformCallback", "res = ${response.body()}")
        Log.e("ReformCallback", "res = ${response.code()}")
        Log.e("ReformCallback", "res = ${response.headers()}")
        Log.e("ReformCallback", "res = ${response.message()}")
        Log.e("ReformCallback", "res = ${response.errorBody()}")

        if(response.isSuccessful) {
            val body = response.body()
            when (val code = response.code()) {
                HttpResponseCode.SUCCESS -> {
                    listener.successResponse(body!!)
                }
                
                HttpResponseCode.TOKEN_EXPIRED_ERROR -> {
                    Log.e("TOKEN_EXPIRED_ERROR", "토큰 만료됨.")
                    listener.errorResponse(code)
                    //reissueTokenCall(call)
                }

                HttpResponseCode.PARAMETER_ERROR -> {
                    Log.e("PARAMETER_ERROR", "error code = ${code}")
                    application.showToast("입력 정보를 확인해주세요.")
                }
                HttpResponseCode.NOT_FOUND -> {

                }
                HttpResponseCode.INTERNAL_SERVER_ERROR -> {
                    application.showToast("일시적인 에러가 발생했습니다. INTERNAL_SERVER_ERROR = ${code}")
                }

                HttpResponseCode.TYPE_ERROR1 -> { }
                HttpResponseCode.TYPE_ERROR2 -> { }
                HttpResponseCode.TYPE_ERROR3 -> { }
                else -> {
                    Log.e("Other Error", "error code = ${code}")
                    application.showToast("일시적인 에러가 발생했습니다. Error Code = ${code}")
                }
            }
        } else {
            Log.e("PARAMETER_ERROR", "error code = ${response.errorBody()!!.string()}")
            application.showToast("일시적인 에러가 발생했습니다. Error = ${response.errorBody()!!.string()}")
        }
    }

    override fun onFailure(call: Call<T>, t: Throwable) {
        Log.e("ReformCallback", "failure = ${call.request().header("Authorization")}")
        Log.e("ReformCallback", "failure = ${t.message!!}")
        t.printStackTrace()
    }

	//재시도함수
    private fun reissueTokenCall(call: Call<T>) {
        call.clone().enqueue(this)
    }
}

HttpResponseCode

object HttpResponseCode {
    const val SUCCESS = 200 /** 성공 */

    const val PARAMETER_ERROR = 400 /** 파라미터 에러 */
    const val TOKEN_EXPIRED_ERROR = 401 /** When access token or refresh token expired*/
    const val NOT_FOUND = 404 /** 404 NOT FOUND */
    const val INTERNAL_SERVER_ERROR = 500 /** 인터널 서버 에러 */
    const val TYPE_ERROR1 = 501 /** */
    const val TYPE_ERROR2 = 502 /** */
    const val TYPE_ERROR3 = 503 /** */
}
반응형