メインコンテンツまでスキップ

Response:getResponseCode()

レスポンスから HTTP ステータスコードを取得します。

シグネチャ

getResponseCode(): number

戻り値

number - HTTP ステータスコード(例: 200、404、500)

説明

getResponseCode() メソッドは、サーバーレスポンスから HTTP ステータスコードを返します。ステータスコードは、HTTP リクエストが成功したか、失敗したか、さらなるアクションが必要かを示します。

基本的なステータスコードの確認

-- リクエストを作成してステータスコードを確認
local response = Request("https://api.example.com/users"):get()
local statusCode = response:getResponseCode()

if statusCode == 200 then
print("Request successful!")
local data = response:getData()
print("Response data: " .. data)
else
print("Request failed with status: " .. statusCode)
end

包括的なステータスコードの処理

local response = Request("https://api.example.com/data"):get()
local status = response:getResponseCode()

if status >= 200 and status < 300 then
-- 成功レスポンス(2xx)
print("Request successful (2xx)")
local data = response:getData()
print("Data: " .. data)

elseif status >= 300 and status < 400 then
-- リダイレクトレスポンス(3xx)
print("Redirection received (3xx)")
print("Status: " .. status)

elseif status >= 400 and status < 500 then
-- クライアントエラーレスポンス(4xx)
print("Client error (4xx)")
local errorData = response:getData()
if errorData and errorData ~= "" then
print("Error details: " .. errorData)
end

elseif status >= 500 and status < 600 then
-- サーバーエラーレスポンス(5xx)
print("Server error (5xx)")
local errorData = response:getData()
if errorData and errorData ~= "" then
print("Server error details: " .. errorData)
end

else
print("Unexpected status code: " .. status)
end

個別のステータスコードの処理

local response = Request("https://api.example.com/users/123"):get()
local status = response:getResponseCode()

if status == 200 then
print("OK - Request successful")
local userData = response:getData()
print("User data: " .. userData)

elseif status == 201 then
print("Created - Resource created successfully")
local newResource = response:getData()
print("New resource: " .. newResource)

elseif status == 204 then
print("No Content - Request successful, no response body")

elseif status == 400 then
print("Bad Request - Invalid request data")
local errorInfo = response:getData()
print("Error: " .. errorInfo)

elseif status == 401 then
print("Unauthorized - Authentication required")

elseif status == 403 then
print("Forbidden - Access denied")

elseif status == 404 then
print("Not Found - Resource does not exist")

elseif status == 500 then
print("Internal Server Error")
local serverError = response:getData()
print("Server error details: " .. serverError)

else
print("Other status: " .. status)
local otherData = response:getData()
if otherData and otherData ~= "" then
print("Response: " .. otherData)
end
end

HTTP メソッド別のステータスコード

-- GET リクエスト
local getResponse = Request("https://api.example.com/data"):get()
local getStatus = getResponse:getResponseCode()

if getStatus == 200 then
print("Data retrieved successfully")
elseif getStatus == 404 then
print("Data not found")
end

-- POST リクエスト
local postResponse = Request("https://api.example.com/users")
:setParameter("name", "John")
:setParameter("email", "john@example.com")
:post()

local postStatus = postResponse:getResponseCode()

if postStatus == 201 then
print("User created successfully")
local newUser = postResponse:getData()
print("Created user: " .. newUser)
elseif postStatus == 400 then
print("Invalid user data")
elseif postStatus == 409 then
print("User already exists")
end

-- DELETE リクエスト
local deleteResponse = Request("https://api.example.com/users/123"):delete()
local deleteStatus = deleteResponse:getResponseCode()

if deleteStatus == 204 then
print("User deleted successfully")
elseif deleteStatus == 404 then
print("User not found")
end

ステータスコードのヘルパー関数

function handleResponse(response)
local status = response:getResponseCode()
local data = response:getData()

-- 成功(2xx)
if status >= 200 and status < 300 then
print("✓ Request successful (" .. status .. ")")
if data and data ~= "" then
return data
else
return "Success (no content)"
end
end

-- クライアントエラー(4xx)
if status >= 400 and status < 500 then
print("✗ Client error (" .. status .. ")")
if data and data ~= "" then
print("Error details: " .. data)
end
return nil
end

-- サーバーエラー(5xx)
if status >= 500 and status < 600 then
print("✗ Server error (" .. status .. ")")
if data and data ~= "" then
print("Server error: " .. data)
end
return nil
end

print("? Unexpected status: " .. status)
return nil
end

-- 使用例
local response = Request("https://api.example.com/data"):get()
local result = handleResponse(response)

if result then
print("Operation successful: " .. result)
else
print("Operation failed")
end

API リトライロジック

function makeRequestWithRetry(url, maxRetries)
local retries = 0

while retries < maxRetries do
local response = Request(url):get()
local status = response:getResponseCode()

-- 成功
if status == 200 then
return response:getData()
end

-- クライアントエラー(4xx)の場合はリトライしない
if status >= 400 and status < 500 then
print("Client error (" .. status .. "), not retrying")
return nil
end

-- サーバーエラー(5xx)の場合はリトライ
if status >= 500 and status < 600 then
retries = retries + 1
print("Server error (" .. status .. "), retrying... (" .. retries .. "/" .. maxRetries .. ")")
-- リトライ前に待機する(ここで遅延を追加するとよいでしょう)
else
retries = retries + 1
print("Unexpected status (" .. status .. "), retrying... (" .. retries .. "/" .. maxRetries .. ")")
end
end

print("Max retries reached, giving up")
return nil
end

local data = makeRequestWithRetry("https://api.example.com/unstable", 3)
if data then
print("Request succeeded: " .. data)
end

一般的な HTTP ステータスコード

コードカテゴリ意味一般的な用途
200成功OKリクエスト成功
201成功Createdリソース作成済み
204成功No Content成功、レスポンスボディなし
400クライアントエラーBad Request無効なリクエストデータ
401クライアントエラーUnauthorized認証が必要
403クライアントエラーForbiddenアクセス拒否
404クライアントエラーNot Foundリソースが存在しない
409クライアントエラーConflictリソースの競合
500サーバーエラーInternal Server Errorサーバー側のエラー
502サーバーエラーBad Gateway無効な上流レスポンス
503サーバーエラーService Unavailableサーバーが一時的に利用不可

注記

  • レスポンスデータを処理する前に、必ずステータスコードを確認してください
  • ステータスコードは HTTP/1.1 と HTTP/2 で標準化されています
  • 2xx は成功、3xx はリダイレクト、4xx はクライアントエラー、5xx はサーバーエラーを示します
  • 一部の API では、独自のステータスコードや非標準の意味を使用する場合があります
  • エラーレスポンス(4xx、5xx)には、レスポンスボディに有用な情報が含まれている場合があります
  • ネットワークエラーやタイムアウトにより、レスポンスオブジェクト自体が作成されない場合があります