Skip to content

Instantly share code, notes, and snippets.

@dragneelfps
Last active February 21, 2020 09:16
Show Gist options
  • Save dragneelfps/a78728fe181098c4d5cd5991a2093987 to your computer and use it in GitHub Desktop.
Save dragneelfps/a78728fe181098c4d5cd5991a2093987 to your computer and use it in GitHub Desktop.
New kind of logging and exception mapping. WIP
package com.expedia.ord.recon
import java.util.*
fun main(args: Array<String>) {
val helloApp = HelloApp()
helloApp.work()
helloApp.funstuff("skiing")
try {
val asd = helloApp.otherstuff(10)
println("otherstuff: $asd")
val asd2 = helloApp.otherstuff(-1)
println("otherstuff: $asd2")
} catch (ex: CustomError) {
println("Custom error caught: $ex")
}
}
class HelloApp {
fun work() = logging {
println("working...")
return@logging 1
}
fun funstuff(stuff: String) = messageLogging(stuff) {
println("having fun...")
1
}
fun otherstuff(value: Int) = exceptionMapper(ExceptionMapper()) {
if (value < 0) {
throw IllegalArgumentException("otherstuff args")
} else {
work()
value + 10
}
}
}
fun <T> exceptionMapper(mapper: ExceptionMapper<T>, method: () -> T): T {
return try {
method.invoke()
} catch (ex: Exception) {
mapper.map(ex)
}
}
class ExceptionMapper<T> {
fun map(ex: Exception): T {
throw CustomError(ex)
}
}
class CustomError(ex: Exception) : RuntimeException(ex)
fun <T> messageLogging(stuffName: String, method: () -> T) = logging(
mapOf(
"REQUEST_ID" to UUID.randomUUID(),
"Stuff_Name" to stuffName
)
, method
)
fun <T> logging(logMap: Map<String, Any> = emptyMap(), method: () -> T): T {
if (logMap.isNotEmpty()) println(logMap)
val result = method.invoke()
println("End")
return result
}
@dragneelfps
Copy link
Author

Motivation

  • Kotlin first
  • Spring AOP does not allow same class method calls
  • AspectJ is too complicated to setup and problems with kotlin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment