Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

avoid crash when http response is not json #1185

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 20 additions & 11 deletions app/src/main/java/org/anitab/mentorship/utils/CommonUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
}
}
Expand Down