[英]How to properly check the HTTP response code in Ruby
我正在编写一个gem,它将作为我公司提供的服务的REST API客户端。
为此,我有一个Channel
类,它将作为与API的/channels
路径交互的手段。 它使用HTTParty
进行实际的HTTP调用。 该类有一个名为create的方法,它使用必需的属性POST一个Channel实例。
这是方法的样子:
def create
body = { external_id: external_id,
name: name,
description: description }
action = post "/", body
case action.response.class
when Net::HTTPAccepted then return action
when Net::HTTPNotAcceptable then raise HTTPNotAcceptable
else raise "Server responded with " + Net::HTTPResponse::CODE_TO_OBJ[action.response.code].to_s
end
end
post
方法是一种抽象,它将主体哈希转换为JSON,并将身份验证和其他属性附加到实际的HTTParty
调用。
这不起作用。 即使响应是202
,这个case
语句总是落在else
条件下。 我在post
调用后附加了一个pry
会话来验证响应是否正确:
38: def create
39: body = { external_id: external_id,
40: name: name,
41: description: description }
42: action = post "/", body
=> 43: case action.response.class
44: when Net::HTTPAccepted then return action
45: when Net::HTTPNotAcceptable then raise HTTPNotAcceptable
46: else raise "Server responded with " + Net::HTTPResponse::CODE_TO_OBJ[action.response.code].to_s
47: end
48: end
[1] (pry) #<ZynkApi::Channel>: 0> action.response.class
=> Net::HTTPAccepted
但它仍然落在else
:
[1] (pry) #<ZynkApi::Channel>: 0> action.response.class
=> Net::HTTPAccepted
[2] (pry) #<ZynkApi::Channel>: 0> n
From: /Users/cassiano/projects/Zynk/src/zynk_api/lib/zynk_api/channel.rb @ line 38 ZynkApi::Channel#create:
38: def create
39: body = { external_id: external_id,
40: name: name,
41: description: description }
42: action = post "/", body
43: case action.response.class
44: when Net::HTTPAccepted then return action
45: when Net::HTTPNotAcceptable then raise HTTPNotAcceptable
=> 46: else raise "Server responded with " + Net::HTTPResponse::CODE_TO_OBJ[action.response.code].to_s
47: end
48: end
考虑使用===
方法的case语句:
if Net::HTTPAccepted === action.response.class
puts 'accepted'
elsif Net::HTTPNotAcceptable === action.response.class
puts 'not acceptable'
else
puts 'unknown status'
end
但是,如你所知 - 大多数类的类都是一个类,所以你应该像这样重写你的情况(不要在响应时调用类方法):
case action.response
when Net::HTTPAccepted
return action
when Net::HTTPNotAcceptable
raise HTTPNotAcceptable
else
raise "Server responded with " + Net::HTTPResponse::CODE_TO_OBJ[action.response.code].to_s
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.