Skip to content

Commit 6954bcc

Browse files
Provide a means to customize exception logging (#40)
1 parent c9adebd commit 6954bcc

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

router/src/main/kotlin/io/moia/router/RequestHandler.kt

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,16 +82,28 @@ abstract class RequestHandler : RequestHandler<APIGatewayProxyRequestEvent, APIG
8282
private fun exceptionToResponseEntity(e: Exception, input: APIGatewayProxyRequestEvent) =
8383
when (e) {
8484
is ApiException -> e.toResponseEntity(this::createErrorBody)
85-
.also { log.info("Caught api error while handling ${input.httpMethod} ${input.path} - $e") }
85+
.also { logApiException(e, input) }
8686
else -> exceptionToResponseEntity(e)
87-
.also {
88-
log.error("Caught exception handling ${input.httpMethod} ${input.path} - $e", e)
89-
}
87+
.also { logUnknownException(e, input) }
9088
}
9189

9290
private fun missingPermissions(input: APIGatewayProxyRequestEvent, routerFunction: RouterFunction<Any, Any>) =
9391
!permissionHandlerSupplier()(input).hasAnyRequiredPermission(routerFunction.requestPredicate.requiredPermissions)
9492

93+
/**
94+
* Hook to be able to override the way ApiExceptions are logged.
95+
*/
96+
open fun logApiException(e: ApiException, input: APIGatewayProxyRequestEvent) {
97+
log.info("Caught api error while handling ${input.httpMethod} ${input.path} - $e")
98+
}
99+
100+
/**
101+
* Hook to be able to override the way non-ApiExceptions are logged.
102+
*/
103+
open fun logUnknownException(e: Exception, input: APIGatewayProxyRequestEvent) {
104+
log.error("Caught exception handling ${input.httpMethod} ${input.path} - $e", e)
105+
}
106+
95107
open fun serializationHandlers(): List<SerializationHandler> = listOf(
96108
JsonSerializationHandler(objectMapper)
97109
)
@@ -162,6 +174,11 @@ abstract class RequestHandler : RequestHandler<APIGatewayProxyRequestEvent, APIG
162174

163175
private fun createUnprocessableEntityErrorBody(error: UnprocessableEntityError): Any = createUnprocessableEntityErrorBody(listOf(error))
164176

177+
/**
178+
* Hook to customize the way non-ApiExceptions are converted to ResponseEntity.
179+
*
180+
* Some common exceptions are already handled in the default implementation.
181+
*/
165182
open fun exceptionToResponseEntity(ex: Exception) =
166183
when (ex) {
167184
is JsonParseException -> ResponseEntity(

0 commit comments

Comments
 (0)