programing

HTTParty로 오류를 어떻게 처리 할 수 ​​있습니까?

nasanasas 2020. 11. 1. 18:11
반응형

HTTParty로 오류를 어떻게 처리 할 수 ​​있습니까?


HTTParty를 사용하여 HTTP 요청을 만드는 Rails 애플리케이션을 개발 중입니다. HTTParty로 HTTP 오류를 어떻게 처리 할 수 ​​있습니까? 특히, HTTP 502 & 503 및 연결 거부 및 시간 초과 오류와 같은 기타 오류를 포착해야합니다.


HTTParty :: Response 의 인스턴스 code에는 HTTP 응답의 상태 코드를 포함 하는 속성이 있습니다. 정수로 주어집니다. 따라서 다음과 같습니다.

response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')

case response.code
  when 200
    puts "All good!"
  when 404
    puts "O noes not found!"
  when 500...600
    puts "ZOMG ERROR #{response.code}"
end

이 답변은 연결 실패를 해결합니다. URL을 찾을 수없는 경우 상태 코드가 도움이되지 않습니다. 다음과 같이 구하십시오.

 begin
   HTTParty.get('http://google.com')
 rescue HTTParty::Error
   # don´t do anything / whatever
 rescue StandardError
   # rescue instances of StandardError,
   # i.e. Timeout::Error, SocketError etc
 end

자세한 내용은 이 github 문제를 참조하십시오.


당신은 또한 같은 편리한 조건 방법을 사용할 수 있습니다 success?또는 bad_gateway?이러한 방법을 :

response = HTTParty.post(uri, options)
p response.success?

가능한 응답의 전체 목록은 Rack::Utils::SYMBOL_TO_STATUS_CODEconstant 에서 찾을 수 있습니다 .

참고 URL : https://stackoverflow.com/questions/7909596/how-can-i-handle-errors-with-httparty

반응형