Desenvolvimento Ophos
Desenvolvimento Ophos

Reputation: 65

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()
    }
}

Upvotes: 2

Views: 5149

Answers (2)

sol4me
sol4me

Reputation: 15708

You are not throwing an exception anywhere, hence catch block is not getting executed. Here is updated code.


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

You can check the response header via curl . E.g. curl -v -X DELETE http://YOUR_API_URL

Upvotes: 1

Rivu Chakraborty
Rivu Chakraborty

Reputation: 1372

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() }
 }

Upvotes: 4

Related Questions