Response:getResponseCode()
يحصل على رمز حالة HTTP من الاستجابة.
التوقيع
getResponseCode(): number
القيمة المعادة
number - رمز حالة HTTP (مثلًا 200 أو 404 أو 500)
الوصف
تُعيد الدالة getResponseCode() رمز حالة HTTP من استجابة الخادم. تشير رموز الحالة إلى ما إذا كان طلب HTTP ناجحًا أو فاشلًا أو يتطلب إجراءً إضافيًا.
أمثلة
التحقق الأساسي من رمز الحالة
-- Make a request and check the status code
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
-- Success responses (2xx)
print("Request successful (2xx)")
local data = response:getData()
print("Data: " .. data)
elseif status >= 300 and status < 400 then
-- Redirection responses (3xx)
print("Redirection received (3xx)")
print("Status: " .. status)
elseif status >= 400 and status < 500 then
-- Client error responses (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
-- Server error responses (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 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
دالة مساعدة لرمز الحالة
function handleResponse(response)
local status = response:getResponseCode()
local data = response:getData()
-- Success (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
-- Client errors (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
-- Server errors (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
-- Usage
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
منطق إعادة محاولة الطلب
function makeRequestWithRetry(url, maxRetries)
local retries = 0
while retries < maxRetries do
local response = Request(url):get()
local status = response:getResponseCode()
-- Success
if status == 200 then
return response:getData()
end
-- Don't retry on client errors (4xx)
if status >= 400 and status < 500 then
print("Client error (" .. status .. "), not retrying")
return nil
end
-- Retry on server errors (5xx)
if status >= 500 and status < 600 then
retries = retries + 1
print("Server error (" .. status .. "), retrying... (" .. retries .. "/" .. maxRetries .. ")")
-- Wait before retrying (you might want to add a delay here)
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) قد تحتوي على معلومات مفيدة في متن الاستجابة
- قد تمنع أخطاء الشبكة أو انتهاء المهلة إنشاء كائن استجابة تمامًا