다음 코드는 Apache HTTP Client를 사용하는 외부 시스템 (Capsule CRM)에 연결하는 코드입니다.Kotlin에서 HTTP 클라이언트를 사용할 때 오류를 올바르게 처리하는 방법은 무엇입니까?
override fun findPartiesByUrlFragment(urlFragment: String): PartiesSearchResult {
val req = HttpGet("https://api.capsulecrm.com/api/v2/parties/search?q=${urlFragment}")
req.setHeader("Authorization", "Bearer ${ApiToken}")
req.setHeader("Accept", "application/json");
val httpClient = HttpClients.createDefault()
val res = httpClient.execute(req)
val parser = Parser()
val json:JsonObject = parser.parse(res.entity.content) as JsonObject
[...] // What happens thereafter isn't relevant because most errors are likely to occur in the code above
return PartiesSearchResult(false, "", emptyList())
}
이 코드 조각 그러므로 내가 바로 오류 처리를하고 전체 응용 프로그램이 충돌하지 않도록해야 24를 실행하는 응용 프로그램에서 작동해야하며, 예상 문제 (예를 들면 캡슐의 서버의 경우 아래로)가 발생합니다. false
이 PartiesSearchResult(false, "", emptyList())
이면 작업이 실패했음을 의미합니다. 내가 할 수있는
는 HTTP 응답 코드를 chesk하고 200
있어하지만 (자바 반대) 어떤 여기에 예외를 선언 보지 않기 때문에 나는 혼란 스러워요 경우에만 응답을 구문 분석합니다.
지금 내가이 작업을 수행 할 수 :
override fun findPartiesByUrlFragment(urlFragment: String): PartiesSearchResult {
var httpClient = null
var res = null
try {
val req = HttpGet("https://api.capsulecrm.com/api/v2/parties/search?q=${urlFragment}")
req.setHeader("Authorization", "Bearer ${ApiToken}")
req.setHeader("Accept", "application/json");
httpClient = HttpClients.createDefault()
res = httpClient.execute(req)
if (res == null) {
return PartiesSearchResult(false, "null response", emptyList())
}
if (res.entity == null) {
return PartiesSearchResult(false, "null entity", emptyList())
}
val content = res.entity.content
if (content == null) {
return PartiesSearchResult(false, "null content", emptyList())
}
if (responseCode(res) == 200) {
val parser = Parser()
val json:JsonObject = parser.parse(content) as JsonObject
[...] // Convert JSON to my own objects
return PartiesSearchResult(true, "", emptyList())
}
return PartiesSearchResult(false, "Invalid HTTP response code", emptyList())
}
catch (Throwable t) {
return PartiesSearchResult(false, toString(t), emptyList())
}
finally {
closeIfNotNull(res)
closeIfNotNull(httpClient)
}
return PartiesSearchResult(false, "", emptyList())
}
은 (HTTP 클라이언트를 사용하여 다른 시스템에서 데이터를 가져 오는의 특정 작업) 코 틀린에 오류 처리를 할 수있는 더 나은 방법이 있나요, 만약에 내 시스템이되지해야합니다 예상 된 문제 상황 (외국 서버 다운, 외부 서버 과부하 또는 내부 오류, 일시적인 인터넷 연결 손실 등) 때문에 실패합니까?