@@ -4,31 +4,35 @@ import kotlinx.serialization.*
44import kotlinx.serialization.json.Json
55import net.typedrest.http.HttpStatusCode
66import okhttp3.Response
7- import java.io.IOException
7+ import okhttp3.ResponseBody
88
99/* *
1010 * Handles errors in HTTP responses by mapping status codes to common exception types.
1111 */
12- class DefaultErrorHandler : ErrorHandler {
12+ open class DefaultErrorHandler : ErrorHandler {
1313 @Throws(HttpException ::class )
1414 override fun handle (response : Response ) {
1515 if (response.isSuccessful) return
1616
17- val body = response.body?.string()
18- val message = extractJsonMessage(response, body)
17+ val message = response.body?.let (::extractJsonMessage)
1918 ? : " ${response.request.url} responded with ${response.code} ${response.message} "
2019
2120 throw mapException(HttpStatusCode .parse(response.code) ? : HttpStatusCode .InternalServerError , message, response)
2221 }
2322
24- private fun extractJsonMessage (response : Response , body : String? ): String? {
25- if (body.isNullOrEmpty()) return null
26-
27- val mediaType = response.body?.contentType()?.toString()
28- if (mediaType != " application/json" && (mediaType == null || ! mediaType.endsWith(" +json" ))) return null
23+ /* *
24+ * Tries to extract an error message from the response body.
25+ *
26+ * @param body The response body.
27+ */
28+ protected open fun extractJsonMessage (body : ResponseBody ): String? {
29+ val mediaType = body.contentType()?.toString()
30+ if (mediaType == null || (mediaType != " application/json" && ! mediaType.endsWith(" +json" ))) {
31+ return null
32+ }
2933
3034 return try {
31- val decoded = Json .decodeFromString<JsonErrorResponse >(body)
35+ val decoded = Json .decodeFromString<JsonErrorResponse >(body.string() )
3236 return decoded.message ? : decoded.details
3337 } catch (e: SerializationException ) {
3438 null
@@ -38,7 +42,14 @@ class DefaultErrorHandler : ErrorHandler {
3842 @Serializable
3943 private class JsonErrorResponse (val message : String? , val details : String? = null )
4044
41- private fun mapException (status : HttpStatusCode , message : String , response : Response ? ) =
45+ /* *
46+ * Maps the HTTP status code to an exception.
47+ *
48+ * @param status The status code.
49+ * @param message An error message to include in the exception.
50+ * @param response The HTTP response to include in the exception.
51+ */
52+ protected open fun mapException (status : HttpStatusCode , message : String , response : Response ? ) =
4253 when (status) {
4354 HttpStatusCode .BadRequest -> BadRequestException (message, status, response)
4455 HttpStatusCode .Unauthorized -> AuthenticationException (message, status, response)
0 commit comments