Skip to content

Commit dc8adeb

Browse files
committed
Handle exception during runtime
Previously, exceptions raised during the policy processing phase were ignored unless the on_failed policy was added to the chain. This PR terminates the request and prints the stacktrace by default when an exception is thrown.
1 parent 2f6e61d commit dc8adeb

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

gateway/src/apicast/policy/on_failed/on_failed.lua

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
local get_phase = ngx.get_phase
2+
13
local _M = require('apicast.policy').new('On failed', 'builtin')
24
local new = _M.new
35

@@ -11,6 +13,12 @@ end
1113
function _M:export()
1214
return {
1315
policy_error_callback = function(policy_name, error_message)
16+
local phase = get_phase()
17+
-- skip calling plugins on body_filter/log phase as ngx.exit does not
18+
-- exist in these phases
19+
if phase == "body_filter" or phase == "log" then
20+
return
21+
end
1422
ngx.log(ngx.DEBUG, "Stop request because policy: '", policy_name, "' failed, error='", error_message, "'")
1523
ngx.exit(self.error_status_code)
1624
end

gateway/src/apicast/policy_chain.lua

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,8 @@ local function call_chain(phase_name)
216216
if not status then
217217
if context.policy_error_callback then
218218
context.policy_error_callback(self[i]._NAME, return_val)
219+
else
220+
error(return_val)
219221
end
220222
-- This is important because Openresty just died on error on init
221223
-- phase, and we should keep in this way.

t/apicast-policy-chains-crash.t

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,34 @@ GET /test HTTP/1.1
3232
--- error_code: 200
3333
--- error_log
3434
Policy error_policy crashed in .new()
35+
36+
37+
38+
=== TEST 2: policy chain with a policy that crashes on rewrite/access()
39+
Policies that crash during request phase should ternimate the request
40+
--- configuration
41+
{
42+
"services": [
43+
{
44+
"id": 42,
45+
"proxy": {
46+
"policy_chain" : [
47+
{ "name" : "error_policy", "version" : "2.0.0" },
48+
{ "name" : "apicast.policy.echo" }
49+
]
50+
}
51+
}
52+
]
53+
}
54+
--- request
55+
GET /test
56+
--- ignore_response
57+
--- error_code: 500
58+
--- error_log eval
59+
[
60+
'lua entry thread aborted: runtime error:',
61+
'terminated in rewrite phase',
62+
'stack traceback:',
63+
" in function 'error'",
64+
": in function 'rewrite'",
65+
]

0 commit comments

Comments
 (0)