Skip to content

Commit 605fcc8

Browse files
committed
fix: error handlers that take args: Args crashed instead of running
Error handlers, listener start/completion handlers and middleware error handlers build their kwargs with next_keys_required=False, which removed next/next_ from the available args. Args.__init__ requires next, so a handler declared as (args: Args) raised TypeError and never ran. The original error was then lost. - Keep next/next_ available for building Args and only skip injecting them as direct kwargs when there is no middleware chain - Add an error field to Args and AsyncArgs so error handlers can read the exception through args - Add sync and async tests for an error handler that takes args
1 parent 698687c commit 605fcc8

6 files changed

Lines changed: 63 additions & 11 deletions

File tree

‎slack_bolt/kwargs_injection/args.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ def handle_buttons(args):
111111
"""`next()` utility function, which tells the middleware chain that it can continue with the next one"""
112112
next_: Callable[[], None]
113113
"""An alias of `next()` for avoiding the Python built-in method overrides in middleware functions"""
114+
error: Optional[Exception]
115+
"""The exception raised by a listener or middleware; only set in error handlers"""
114116

115117
def __init__(
116118
self,
@@ -144,6 +146,7 @@ def __init__(
144146
# the naming conflict with the built-in one affects
145147
# only the internals of this method
146148
next: Callable[[], None],
149+
error: Optional[Exception] = None,
147150
**kwargs, # noqa
148151
):
149152
self.logger: logging.Logger = logger
@@ -177,3 +180,4 @@ def __init__(
177180

178181
self.next: Callable[[], None] = next
179182
self.next_: Callable[[], None] = next
183+
self.error: Optional[Exception] = error

‎slack_bolt/kwargs_injection/async_args.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,8 @@ async def handle_buttons(args):
110110
"""`next()` utility function, which tells the middleware chain that it can continue with the next one"""
111111
next_: Callable[[], Awaitable[None]]
112112
"""An alias of `next()` for avoiding the Python built-in method overrides in middleware functions"""
113+
error: Optional[Exception]
114+
"""The exception raised by a listener or middleware; only set in error handlers"""
113115

114116
def __init__(
115117
self,
@@ -140,6 +142,7 @@ def __init__(
140142
save_thread_context: Optional[AsyncSaveThreadContext] = None,
141143
say_stream: Optional[AsyncSayStream] = None,
142144
next: Callable[[], Awaitable[None]],
145+
error: Optional[Exception] = None,
143146
**kwargs, # noqa
144147
):
145148
self.logger: Logger = logger
@@ -173,3 +176,4 @@ def __init__(
173176

174177
self.next: Callable[[], Awaitable[None]] = next
175178
self.next_: Callable[[], Awaitable[None]] = next
179+
self.error: Optional[Exception] = error

‎slack_bolt/kwargs_injection/async_utils.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,6 @@ def build_async_required_kwargs(
6565
# error handler
6666
"error": error, # Exception
6767
}
68-
if not next_keys_required:
69-
all_available_args.pop("next")
70-
all_available_args.pop("next_")
71-
7268
all_available_args["payload"] = (
7369
all_available_args["options"]
7470
or all_available_args["shortcut"]
@@ -98,7 +94,12 @@ def build_async_required_kwargs(
9894
# We are sure that we should skip manipulating this arg
9995
required_arg_names.pop(0)
10096

101-
kwargs: Dict[str, Any] = {k: v for k, v in all_available_args.items() if k in required_arg_names}
97+
# next/next_ are only injectable where a middleware chain exists.
98+
# They stay in all_available_args so an `args` object can still be built.
99+
injectable_names = set(required_arg_names)
100+
if not next_keys_required:
101+
injectable_names -= {"next", "next_"}
102+
kwargs: Dict[str, Any] = {k: v for k, v in all_available_args.items() if k in injectable_names}
102103
found_arg_names = kwargs.keys()
103104
for name in required_arg_names:
104105
if name == "args":

‎slack_bolt/kwargs_injection/utils.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,6 @@ def build_required_kwargs(
6464
# error handler
6565
"error": error, # Exception
6666
}
67-
if not next_keys_required:
68-
all_available_args.pop("next")
69-
all_available_args.pop("next_")
70-
7167
all_available_args["payload"] = (
7268
all_available_args["options"]
7369
or all_available_args["shortcut"]
@@ -97,7 +93,12 @@ def build_required_kwargs(
9793
# We are sure that we should skip manipulating this arg
9894
required_arg_names.pop(0)
9995

100-
kwargs: Dict[str, Any] = {k: v for k, v in all_available_args.items() if k in required_arg_names}
96+
# next/next_ are only injectable where a middleware chain exists.
97+
# They stay in all_available_args so an `args` object can still be built.
98+
injectable_names = set(required_arg_names)
99+
if not next_keys_required:
100+
injectable_names -= {"next", "next_"}
101+
kwargs: Dict[str, Any] = {k: v for k, v in all_available_args.items() if k in injectable_names}
101102
found_arg_names = kwargs.keys()
102103
for name in required_arg_names:
103104
if name == "args":

‎tests/scenario_tests/test_error_handler.py‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from slack_sdk import WebClient
66
from slack_sdk.signature import SignatureVerifier
77

8-
from slack_bolt import BoltRequest, BoltResponse
8+
from slack_bolt import Args, BoltRequest, BoltResponse
99
from slack_bolt.app import App
1010
from slack_bolt.error import BoltUnhandledRequestError
1111
from tests.mock_web_api_server import (
@@ -153,6 +153,26 @@ def failing_listener():
153153
assert response.status == 500
154154
assert response.headers["x-test-result"] == ["1"]
155155

156+
def test_custom_with_args(self):
157+
called = []
158+
159+
def error_handler(args: Args):
160+
assert isinstance(args.error, Exception)
161+
args.response.headers["x-test-result"] = ["1"]
162+
called.append(True)
163+
164+
def failing_listener():
165+
raise Exception("Something wrong!")
166+
167+
app = App(client=self.web_client, signing_secret=self.signing_secret)
168+
app.error(error_handler)
169+
app.action("a")(failing_listener)
170+
171+
response = app.dispatch(self.build_valid_request())
172+
assert response.status == 500
173+
assert response.headers["x-test-result"] == ["1"]
174+
assert called == [True]
175+
156176
def test_unhandled_errors(self):
157177
app = App(
158178
client=self.web_client,

‎tests/scenario_tests_async/test_error_handler.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from slack_sdk.web.async_client import AsyncWebClient
88

99
from slack_bolt import BoltResponse
10+
from slack_bolt.kwargs_injection.async_args import AsyncArgs
1011
from slack_bolt.async_app import AsyncApp
1112
from slack_bolt.error import BoltUnhandledRequestError
1213
from slack_bolt.request.async_request import AsyncBoltRequest
@@ -163,6 +164,27 @@ async def failing_listener():
163164
assert response.status == 500
164165
assert response.headers["x-test-result"] == ["1"]
165166

167+
@pytest.mark.asyncio
168+
async def test_custom_with_args(self):
169+
called = []
170+
171+
async def error_handler(args: AsyncArgs):
172+
assert isinstance(args.error, Exception)
173+
args.response.headers["x-test-result"] = ["1"]
174+
called.append(True)
175+
176+
async def failing_listener():
177+
raise Exception("Something wrong!")
178+
179+
app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret)
180+
app.error(error_handler)
181+
app.action("a")(failing_listener)
182+
183+
response = await app.async_dispatch(self.build_valid_request())
184+
assert response.status == 500
185+
assert response.headers["x-test-result"] == ["1"]
186+
assert called == [True]
187+
166188
@pytest.mark.asyncio
167189
async def test_unhandled_errors(self):
168190
app = AsyncApp(

0 commit comments

Comments
 (0)