响应状态HTTP SpringBoot Kotlin Api

我从kotlin开始,如果任何人都可以帮助我,我已经有一个关于如何返回http状态的问题,当我的真正的,如果它返回200好,当它的任何其他方式,返回404 NotFound。

我试着按照下面的代码来做,但是在所有情况下,它只返回状态200 OK

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

我认为其他块可以做到这一点

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

你没有在任何地方抛出一个异常,因此catch块没有被执行。 这是更新的代码。

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

你可以通过curl来检查响应头。 例如curl -v -X DELETE http://YOUR_API_URL

Interesting Posts