Chuyển tới nội dung chính

Response:getResponseCode()

Lấy mã trạng thái HTTP từ phản hồi.

Khai báo

getResponseCode(): number

Trả về

number - Mã trạng thái HTTP (ví dụ: 200, 404, 500)

Mô tả

Phương thức getResponseCode() trả về mã trạng thái HTTP từ phản hồi của máy chủ. Mã trạng thái cho biết HTTP request có thành công, thất bại, hay cần hành động thêm.

Ví dụ

Kiểm tra mã trạng thái cơ bản

-- Tạo một request và kiểm tra mã trạng thái
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

Xử lý mã trạng thái toàn diện

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

if status >= 200 and status < 300 then
-- Phản hồi thành công (2xx)
print("Request successful (2xx)")
local data = response:getData()
print("Data: " .. data)

elseif status >= 300 and status < 400 then
-- Phản hồi chuyển hướng (3xx)
print("Redirection received (3xx)")
print("Status: " .. status)

elseif status >= 400 and status < 500 then
-- Phản hồi lỗi máy khách (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
-- Phản hồi lỗi máy chủ (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

Xử lý mã trạng thái cụ thể

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

Mã trạng thái theo phương thức HTTP

-- GET request
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 request
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 request
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

Hàm hỗ trợ mã trạng thái

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

-- Thành công (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

-- Lỗi máy khách (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

-- Lỗi máy chủ (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

-- Cách sử dụng
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

Logic thử lại API

function makeRequestWithRetry(url, maxRetries)
local retries = 0

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

-- Thành công
if status == 200 then
return response:getData()
end

-- Không thử lại với lỗi máy khách (4xx)
if status >= 400 and status < 500 then
print("Client error (" .. status .. "), not retrying")
return nil
end

-- Thử lại với lỗi máy chủ (5xx)
if status >= 500 and status < 600 then
retries = retries + 1
print("Server error (" .. status .. "), retrying... (" .. retries .. "/" .. maxRetries .. ")")
-- Chờ trước khi thử lại (bạn có thể muốn thêm độ trễ ở đây)
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

Các mã trạng thái HTTP phổ biến

NhómÝ nghĩaCách sử dụng điển hình
200Thành côngOKRequest thành công
201Thành côngCreatedTài nguyên đã được tạo
204Thành côngNo ContentThành công, không có thân phản hồi
400Lỗi máy kháchBad RequestDữ liệu request không hợp lệ
401Lỗi máy kháchUnauthorizedYêu cầu xác thực
403Lỗi máy kháchForbiddenTừ chối truy cập
404Lỗi máy kháchNot FoundTài nguyên không tồn tại
409Lỗi máy kháchConflictXung đột tài nguyên
500Lỗi máy chủInternal Server ErrorLỗi phía máy chủ
502Lỗi máy chủBad GatewayPhản hồi upstream không hợp lệ
503Lỗi máy chủService UnavailableMáy chủ tạm thời không khả dụng

Lưu ý

  • Luôn kiểm tra mã trạng thái trước khi xử lý dữ liệu phản hồi
  • Mã trạng thái được tiêu chuẩn hóa trên HTTP/1.1 và HTTP/2
  • Mã 2xx chỉ thành công, 3xx chỉ chuyển hướng, 4xx chỉ lỗi máy khách, 5xx chỉ lỗi máy chủ
  • Một số API có thể dùng mã trạng thái tùy chỉnh hoặc ý nghĩa không chuẩn
  • Phản hồi lỗi (4xx, 5xx) có thể chứa thông tin hữu ích trong thân phản hồi
  • Lỗi mạng hoặc hết thời gian chờ có thể ngăn hoàn toàn đối tượng phản hồi được tạo ra