Skip to content

Commit f71dce1

Browse files
asteedAndy Steed
andauthored
fix: Generalize response status code handling (#87)
* fix: handle extended status * fix: generalize the http status code returned to nginx when required --------- Co-authored-by: Andy Steed <andsteed@adobe.com>
1 parent d4738b4 commit f71dce1

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

src/lua/api-gateway/validation/validator.lua

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,25 @@ function BaseValidator:executeTtl(key)
255255
end
256256
end
257257

258+
-- converts a response status to a valid HTTP status code
259+
function BaseValidator:convertToValidHttpStatusCode(response_status)
260+
response_status = tonumber(response_status)
261+
if response_status == nil then
262+
return 500
263+
end
264+
if (response_status >= 100 and response_status <= 599) then
265+
return response_status
266+
end
267+
268+
local http_code_str = string.sub(tostring(response_status), 1, 3)
269+
local http_code_number = tonumber(http_code_str)
270+
if http_code_number ~= nil and http_code_number >= 100 and http_code_number <= 599 then
271+
return http_code_number
272+
end
273+
274+
ngx.log(ngx.DEBUG, "Status code: ", tostring(response_status), " is not in a valid HTTP Status Code format")
275+
return 500
276+
end
258277

259278
-- generic exit function for a validator --
260279
function BaseValidator:exitFn(status, resp_body)
@@ -269,7 +288,7 @@ function BaseValidator:exitFn(status, resp_body)
269288
end
270289
end
271290

272-
ngx.status = status
291+
ngx.status = self:convertToValidHttpStatusCode(status)
273292

274293
if (ngx.null ~= resp_body) then
275294
ngx.say(resp_body)

src/lua/api-gateway/validation/validatorsHandlerErrorDecorator.lua

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,15 @@ function ValidatorHandlerErrorDecorator:decorateResponse(response_status, respon
109109
response_status = tonumber(response_status)
110110

111111
local o = getResponsesTemplate()[response_status]
112+
-- If no match by status code (e.g. status was converted from an extended error_code like 401013 to 401),
113+
-- try to extract the error_code from the response body and look up by that instead.
114+
if (o == nil and response_body ~= nil and #response_body > 0 and response_body ~= "nil\n") then
115+
local ok, json_body = pcall(cjson.decode, response_body)
116+
if ok and json_body and json_body.error_code then
117+
o = getResponsesTemplate()[tonumber(json_body.error_code)]
118+
end
119+
end
120+
112121
if (o ~= nil) then
113122
ngx.status = self:convertToValidHttpStatusCode(o.http_status)
114123
-- NOTE: assumption: for the moment if it's custom, then it's application/json

0 commit comments

Comments
 (0)