/
error_handlers.lua
83 lines (64 loc) 路 1.93 KB
/
error_handlers.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
local kong = kong
local find = string.find
local fmt = string.format
local utils = require "kong.tools.utils"
local CONTENT_TYPE = "Content-Type"
local ACCEPT = "Accept"
local TYPE_GRPC = "application/grpc"
local BODIES = {
[400] = "Bad request",
[404] = "Not found",
[405] = "Method not allowed",
[408] = "Request timeout",
[411] = "Length required",
[412] = "Precondition failed",
[413] = "Payload too large",
[414] = "URI too long",
[417] = "Expectation failed",
[494] = "Request header or cookie too large",
[500] = "An unexpected error occurred",
[502] = "An invalid response was received from the upstream server",
[503] = "The upstream server is currently unavailable",
[504] = "The upstream server is timing out",
}
local get_body
do
local DEFAULT_FMT = "The upstream server responded with %d"
get_body = function(status)
local body = BODIES[status]
if body then
return body
end
body = fmt(DEFAULT_FMT, status)
BODIES[status] = body
return body
end
end
return function(ctx)
local accept_header = kong.request.get_header(ACCEPT)
if accept_header == nil then
accept_header = kong.request.get_header(CONTENT_TYPE)
if accept_header == nil then
accept_header = kong.configuration.error_default_type
end
end
local status = kong.response.get_status()
local message = get_body(status)
local headers
if find(accept_header, TYPE_GRPC, nil, true) == 1 then
message = { message = message }
else
local mime_type = utils.get_response_type(accept_header)
message = fmt(utils.get_error_template(mime_type), message)
headers = { [CONTENT_TYPE] = mime_type }
end
-- Reset relevant context values
ctx.buffered_proxying = nil
ctx.response_body = nil
if ctx then
ctx.delay_response = nil
ctx.delayed_response = nil
ctx.delayed_response_callback = nil
end
return kong.response.exit(status, message, headers)
end