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)은 응답 본문에 유용한 정보를 포함할 수 있습니다.
- 네트워크 에러나 시간 초과로 인해 응답 객체가 아예 생성되지 않을 수 있습니다.