api - 响应状态 HTTP SpringBoot Kotlin Api

标签 api spring-boot kotlin microservices

我从 kotlin 开始,如果有人可以帮助我,我有一个关于如何返回 http 状态的问题,当我的 true 时,如果它返回 200 Ok,当它是任何其他方式时,返回 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()
    }
}

最佳答案

我认为 else block 可以做到这一点

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

关于api - 响应状态 HTTP SpringBoot Kotlin Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47181503/

相关文章:

java - 如何在旅途中从 Java Spring Controller 的 GUI 下载 CSV 文件?

java - Android:如何以编程方式启用/禁用 Wifi 或 Internet 连接

javascript - 如何在网站中使用天气 API

api - 需要 iPhone GPS(位置)API 链接

ruby - 是否有等效于 Node.js(云存储 API)的 ruby​​ Fog gem?

android - Android Kotlin:不会为EditText触发onTextChanged

scala - JVM 语言中如何编译嵌套函数和词法作用域?

python - API 错误解释带有特殊字符的密码

java - (Spring boot)Optional<>Class可以像List<>Class一样吗?

spring-boot - Spring Boot management.trace.include配置实例