Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Modal.on_error #1167

Merged
merged 2 commits into from
Mar 17, 2022
Merged
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
45 changes: 33 additions & 12 deletions discord/ui/modal.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import os
import sys
from itertools import groupby
import traceback
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

from .input_text import InputText
Expand Down Expand Up @@ -125,6 +126,23 @@ def to_dict(self):
"components": self.to_components(),
}

async def on_error(self, error: Exception, interaction: Interaction) -> None:
"""|coro|

A callback that is called when the modal's callback fails with an error.

The default implementation prints the traceback to stderr.

Parameters
-----------
error: :class:`Exception`
The exception that was raised.
interaction: :class:`~discord.Interaction`
The interaction that led to the failure.
"""
print(f"Ignoring exception in modal {self}:", file=sys.stderr)
traceback.print_exception(error.__class__, error, error.__traceback__, file=sys.stderr)


class _ModalWeights:
__slots__ = ("weights",)
Expand Down Expand Up @@ -184,15 +202,18 @@ async def dispatch(self, user_id: int, custom_id: str, interaction: Interaction)
if value is None:
return

components = [
component
for parent_component in interaction.data["components"]
for component in parent_component["components"]
]
for component in components:
for child in value.children:
if child.custom_id == component["custom_id"]: # type: ignore
child.refresh_state(component)
break
await value.callback(interaction)
self.remove_modal(value, user_id)
try:
components = [
component
for parent_component in interaction.data["components"]
for component in parent_component["components"]
]
for component in components:
for child in value.children:
if child.custom_id == component["custom_id"]: # type: ignore
child.refresh_state(component)
break
await value.callback(interaction)
self.remove_modal(value, user_id)
except Exception as e:
return await value.on_error(e, interaction)