Skip to content

Commit

Permalink
fix(common) #120: Include Message Routing Headers in error responses.
Browse files Browse the repository at this point in the history
  • Loading branch information
andacata committed Jul 22, 2024
1 parent cbfbdb5 commit 4ad47d0
Showing 1 changed file with 14 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,14 @@ fun OcpiException.toHttpResponse(): HttpResponse =
* @return the HttpResponse properly formatted according to the body generated by fn()
*/
@Suppress("UNCHECKED_CAST")
suspend fun <T> HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody<T>): HttpResponse =
try {
suspend fun <T> HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody<T>): HttpResponse {
var baseHeaders = mapOf(Header.CONTENT_TYPE to ContentType.APPLICATION_JSON)

return try {
baseHeaders = baseHeaders
.plus(getDebugHeaders())
.plus(currentResponseMessageRoutingHeadersOrNull()?.httpHeaders().orEmpty())

val ocpiResponseBody = fn()
val isPaginated = ocpiResponseBody.data is SearchResult<*>

Expand All @@ -125,6 +131,7 @@ suspend fun <T> HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody<T>):
} else {
HttpStatus.NOT_FOUND
}

OcpiStatus.CLIENT_INVALID_PARAMETERS.code -> HttpStatus.BAD_REQUEST
else -> HttpStatus.OK
},
Expand All @@ -140,9 +147,7 @@ suspend fun <T> HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody<T>):
ocpiResponseBody
}
),
headers = getDebugHeaders()
.plus(Header.CONTENT_TYPE to ContentType.APPLICATION_JSON)
.plus(currentResponseMessageRoutingHeadersOrNull()?.httpHeaders().orEmpty())
headers = baseHeaders
).let {
if (isPaginated) {
it.copy(
Expand All @@ -155,17 +160,18 @@ suspend fun <T> HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody<T>):
}
} catch (e: OcpiException) {
e.toHttpResponse()
.let { it.copy(headers = it.headers + getDebugHeaders()) }
.let { it.copy(headers = baseHeaders.plus(it.headers)) }
} catch (e: HttpException) {
logger.error(e)
HttpResponse(
status = e.status,
headers = getDebugHeaders()
headers = baseHeaders
)
} catch (e: JsonProcessingException) {
logger.error(e)
HttpResponse(
status = HttpStatus.BAD_REQUEST,
headers = getDebugHeaders()
headers = baseHeaders
)
}
}

0 comments on commit 4ad47d0

Please sign in to comment.