Skip to content

Commit

Permalink
[Add] #18 getErrorMessage,ApiError ,BaseResponseEntity 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
cacaocoffee committed Jun 14, 2024
1 parent 381ecab commit f639c9a
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.sopt.now.data.repositoryimpl.extension

import com.sopt.now.data.dto.response.BaseResponse
import com.sopt.now.domain.entity.ApiError
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import retrofit2.HttpException
import retrofit2.Response

fun Throwable.getErrorMessage(): String {
return when (this) {
is HttpException -> {
val errorBody = response()?.errorBody()?.string() ?: return "Unknown error"
val errorResponse = Json.decodeFromString<BaseResponse<Unit>>(errorBody)
errorResponse.message
}

else -> "An unknown error occurred."
}
}

fun <T> Throwable.handleThrowable(): Result<T> {
return Result.failure(
when (this) {
is HttpException -> ApiError(this.getErrorMessage())
else -> this
}
)
}

fun Response<*>?.getResponseErrorMessage(): String {
val errorBody = this?.errorBody()?.string() ?: return "Unknown error"
val errorResponse = Json.decodeFromString<BaseResponse<Unit>>(errorBody)
return errorResponse.message
}
5 changes: 5 additions & 0 deletions app/src/main/java/com/sopt/now/domain/entity/ApiError.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.sopt.now.domain.entity

data class ApiError(
val errorMessage: String?
) : Exception(errorMessage)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.sopt.now.domain.entity

data class BaseResponseEntity(
val code: Int,
val message: String
)

0 comments on commit f639c9a

Please sign in to comment.