Hey guys, does anybody have a hint for me on how t...
# spring
p
Hey guys, does anybody have a hint for me on how to return from the following .onSuccess?
Copy code
@GetMapping("/{id}")
    fun getEmployeeById(@PathVariable id: Long): ResponseEntity<EntityModel<Employee>> {
        runCatching { getUseCase.getEmployee(id) }
                .onFailure { throw ResourceNotFoundException("User with id $id not found.") }
                .onSuccess {
                    val entityModel = EntityModel(it, linkTo<EmployeeController> { getEmployeeById(id) }.withSelfRel())
                    return ResponseEntity(entityModel, HttpStatus.OK)
                }
    }
getUseCase.getEmployee(id)
can throw an exception that I want to map to an ResourceNotFoundException. I tried to do it in idiomatic Kotlin, but I got stuck at that point. I guess there is another way of achieving this that didn't come up to my mind yet. When there's no exception, the entityModel should be created and returned in an ResponseEntity.
The try catch way would look like the following:
Copy code
@GetMapping("/{id}")
    fun getEmployeeById(@PathVariable id: Long): ResponseEntity<EntityModel<Employee>> {
        val employee = try {
            getUseCase.getEmployee(id)
        } catch (e: EmployeeNotFoundException) {
            throw ResourceNotFoundException("User with id $id not found.")
        }
        val entityModel = EntityModel(employee, linkTo<EmployeeController> { getEmployeeById(id) }.withSelfRel())
        return ResponseEntity(entityModel, HttpStatus.OK)
    }
c
instead of
onSuccess
you should use
map
for this purpose, if your map can through and you want to map that as well, you should use mapCatching. Instead of returning from onSuccess, return the result of
getOrElse
So in the case you describe
Copy code
@GetMapping("/{id}")
fun getEmployeeById(@PathVariable id: Long): ResponseEntity<EntityModel<Employee>> {
    return runCatching { getUseCase.getEmployee(id) }
        .map {
            val entityModel = EntityModel(it, linkTo<EmployeeController> { getEmployeeById(id) }.withSelfRel())
            ResponseEntity(entityModel, HttpStatus.OK)
        }.getOrElse {
            /* optionally log the cause exception: logger.error(it) */

            throw ResourceNotFoundException("User with id $id not found.")
        }
}
p
Thanks for the reply, learned a lot! Its way easier for me to pick up those things on real life examples.
n
Though @Czar sample works I would recommend to look at imperative option using try/catch as well and make comparison yourself.
p
I actually had a try catch there and try to decide right now which one is better.