Search code examples
apispring-bootkotlinmicroservices

Response Status HTTP SpringBoot Kotlin Api


I'm starting in kotlin and if anyone can help me, I've had a question about how I can return the http status, when my true if it returns 200 Ok and when it's any other way, return 404 NotFound.

I tried to do according to the code below, but it is only returning status 200 Ok, in all situations

@DeleteMapping("{id}")
fun delete(@PathVariable id: Long): ResponseEntity<Unit> {
    try {
        if (dogRepository.exists(id)) {
            dogRepository.delete(id)
        }
        return ResponseEntity.ok().build()
    } catch (e: Exception) {
        return ResponseEntity.notFound().build()
    }
}

Solution

  • I think an else block can do that

     @DeleteMapping("{id}") fun delete(@PathVariable id: Long): ResponseEntity<Unit> { 
       try {
                 if (dogRepository.exists(id)) { 
                    dogRepository.delete(id)
                    return ResponseEntity.ok().build()
                } else {
                    return ResponseEntity.notFound().build()
                } 
        } catch (e: Exception) { return ResponseEntity.notFound().build() }
     }