From 6cfd8776b887179b40df2a8e1928c77d79406f87 Mon Sep 17 00:00:00 2001 From: epicadk Date: Mon, 24 Jan 2022 10:08:42 +0530 Subject: [PATCH] avoid crash when http response is not json --- .../anitab/mentorship/utils/CommonUtils.kt | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/org/anitab/mentorship/utils/CommonUtils.kt b/app/src/main/java/org/anitab/mentorship/utils/CommonUtils.kt index 5d354991f..36ee8e4b8 100644 --- a/app/src/main/java/org/anitab/mentorship/utils/CommonUtils.kt +++ b/app/src/main/java/org/anitab/mentorship/utils/CommonUtils.kt @@ -3,6 +3,7 @@ package org.anitab.mentorship.utils import android.util.Log import androidx.annotation.NonNull import com.google.gson.Gson +import com.google.gson.JsonSyntaxException import java.io.IOException import java.util.concurrent.TimeoutException import org.anitab.mentorship.MentorshipApplication @@ -15,36 +16,44 @@ import retrofit2.HttpException */ object CommonUtils { - val gson = Gson() + val gson by lazy { + Gson() + } /** - * Extracts a CustomResponse object from a throwable - * @param throwable from which the object is to be extracted - * @return a CustomResponse object + * Extracts the error message from an httpException + * @param httpException from which the error message is to be extracted + * @return a string containing the error message */ - fun getErrorResponse(@NonNull throwable: Throwable): CustomResponse { - val httpException = throwable as HttpException + private fun getErrorMessage(@NonNull httpException: HttpException): String { val response = httpException.response()?.errorBody()?.string() - return gson.fromJson(response.toString(), CustomResponse::class.java) + ?: return MentorshipApplication.getContext() + .getString(R.string.error_something_went_wrong) + return try { + gson.fromJson(response, CustomResponse::class.java).message + } catch (exception: JsonSyntaxException) { + exception.printStackTrace() + MentorshipApplication.getContext().getString(R.string.error_something_went_wrong) + } } fun getErrorMessage(@NonNull throwable: Throwable, tag: String): String { return when (throwable) { is IOException -> { MentorshipApplication.getContext() - .getString(R.string.error_please_check_internet) + .getString(R.string.error_please_check_internet) } is TimeoutException -> { MentorshipApplication.getContext() - .getString(R.string.error_request_timed_out) + .getString(R.string.error_request_timed_out) } is HttpException -> { - getErrorResponse(throwable).message + getErrorMessage(throwable) } else -> { Log.e(tag, throwable.localizedMessage) MentorshipApplication.getContext() - .getString(R.string.error_something_went_wrong) + .getString(R.string.error_something_went_wrong) } } }