Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/lua/api-gateway/validation/validator.lua
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,25 @@ function BaseValidator:executeTtl(key)
end
end

-- converts a response status to a valid HTTP status code
function BaseValidator:convertToValidHttpStatusCode(response_status)
response_status = tonumber(response_status)
if response_status == nil then
return 500
end
if (response_status >= 100 and response_status <= 599) then
return response_status
end

local http_code_str = string.sub(tostring(response_status), 1, 3)
local http_code_number = tonumber(http_code_str)
if http_code_number ~= nil and http_code_number >= 100 and http_code_number <= 599 then
return http_code_number
end

ngx.log(ngx.DEBUG, "Status code: ", tostring(response_status), " is not in a valid HTTP Status Code format")
return 500
end

-- generic exit function for a validator --
function BaseValidator:exitFn(status, resp_body)
Expand All @@ -269,9 +288,10 @@ function BaseValidator:exitFn(status, resp_body)
end
end

ngx.status = status
ngx.status = self:convertToValidHttpStatusCode(status)

if (ngx.null ~= resp_body) then
ngx.header["Content-Type"] = "application/json"
ngx.say(resp_body)
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,15 @@ function ValidatorHandlerErrorDecorator:decorateResponse(response_status, respon
response_status = tonumber(response_status)

local o = getResponsesTemplate()[response_status]
-- If no match by status code (e.g. status was converted from an extended error_code like 401013 to 401),
-- try to extract the error_code from the response body and look up by that instead.
if (o == nil and response_body ~= nil and #response_body > 0 and response_body ~= "nil\n") then
local ok, json_body = pcall(cjson.decode, response_body)
if ok and json_body and json_body.error_code then
o = getResponsesTemplate()[tonumber(json_body.error_code)]
end
end

if (o ~= nil) then
ngx.status = self:convertToValidHttpStatusCode(o.http_status)
-- NOTE: assumption: for the moment if it's custom, then it's application/json
Expand Down