2017-11-08 5 views
0

kotlin에서 시작하고 누구든지 나를 도울 수 있다면 http 상태를 반환 할 수있는 방법에 대해 질문했습니다. 200 OK를 반환하면 true로 표시하고 다른 메시지는 반환합니다. 방법, 404 NotFound를 반환합니다. 응답 상태 HTTP SpringBoot Kotlin Api

나는 아래의 코드에 따라하려고 노력하지만, 당신은 어디서든 예외, 따라서 catch 블록이 실행 점점되지 않습니다 던지는되지 않습니다

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

답변

0

는 나는 다른 블록이 이해가되지 않습니다 만 다시 그것을 잡으려고 예외를 던지고,이 경우 그

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

고마워요. –

+0

도와 주니 기쁩니다. 이 문제가 해결되면 upvote를 고려해 보시겠습니까? –

+0

예, 점수가 충분하지 않아 계정이 새로 입니다. –

0

만 모든 상황에서, 상태 (200)는 확인을 반환합니다. 여기에 업데이트 된 코드가 있습니다.

 

    @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

+1

을 할 수 있다고 생각합니다. else 브랜치에서 발견되지 않은 것을 리턴하고 try/catch를 제거하는 것이 더 나을 것입니다. –

+0

@PeterHart는 OP가 최소한의 코드를 게시했다고 생각합니다. 이유는 언급하지 않았습니다. 내 코드 업데이트 – sol4me

+0

감사합니다. –