Philipp Mayer
03/31/2020, 11:33 AM@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.Philipp Mayer
03/31/2020, 11:52 AM@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)
}
Czar
04/04/2020, 10:53 AMonSuccess
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
@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.")
}
}
Philipp Mayer
04/04/2020, 12:17 PMnicholasnet
04/05/2020, 2:18 PMPhilipp Mayer
04/05/2020, 2:22 PM