【问题标题】:Response Status HTTP SpringBoot Kotlin Api响应状态 HTTP SpringBoot Kotlin Api
【发布时间】:2018-04-21 05:54:33
【问题描述】:

我从 kotlin 开始,如果有人可以帮助我,我有一个关于如何返回 http 状态的问题,当我返回 200 Ok 时返回 404 NotFound 时返回 404 NotFound。

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

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

【问题讨论】:

    标签: api spring-boot kotlin microservices


    【解决方案1】:

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

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

    【讨论】:

    • 很高兴它对您有所帮助。如果这解决了您的问题,您会考虑投票吗?
    • 是的,但我的分数还不够,我的帐户是新帐户
    • @DesenvolvimentoOphos 没有问题。
    【解决方案2】:

    你没有在任何地方抛出异常,因此 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() } }

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

    【讨论】:

    • 在这种情况下,抛出异常只是为了再次捕获它是没有意义的。最好从 else 分支返回 not found ,并删除 try/catch。
    • @PeterHart,完全同意,认为 OP 发布了最少的代码,这就是为什么没有提到它。更新了我的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多