API: Errors¶
CascadeUI reports a failure in one of three ways, and the kind says what a bot does about it.
- A mistake in how the library is called raises Python's own
TypeError,ValueError, orRuntimeError, where the mistake is made. These are programming errors: the fix belongs in the code, so a bot does not catch them. - A condition a bot may want to handle while it runs raises one of the library's exception classes.
- A Discord call that fails raises discord.py's own exceptions. The library catches them with
DISCORD_CALL_ERRORSwherever a failed call must not stop the work around it.
A message from the library names the class or function, the value it was given, and, where there is one, a line
starting Fix: with the change to make.
Wrong Input¶
A value of the wrong type raises TypeError. A bool counts as the wrong type where a number is expected, since True
is an int in Python. A value of the right type that is out of range, or not one of the options, raises ValueError.
Each is raised at the first point the library can judge the value:
| What is checked | When it raises |
|---|---|
A class attribute (instance_policy, timeout, owner_only, ...) and the hooks a class declares, in the class body or a plain mixin |
When the class is defined, usually at import |
A name that starts with an underscore and replaces one the library's base class uses, in a shape the library cannot call (see PrivateNameWarning) |
When the class is defined |
A constructor or builder argument (card(), choice_row(), Dropdown(...), FormField(...)) |
When the object is built |
A view whose __init__ never reaches the library's, such as one that skips super().__init__() |
When the view is built |
A callable the library calls later (a tab builder, a step condition, a validator, a store subscriber), for the arguments it will be called with |
When it is passed in |
set_class_attribute(name, value) |
At the call, through the same checks as the class attribute, plus a pattern's check that it has room to draw the value (see set_class_attribute()) |
The finished component tree (an empty Container, a label past 80 characters, two components sharing an id) |
At send() and refresh(), and before a push() or pop() edit, before the request reaches Discord. See validate() |
Calls From the Wrong Place¶
RuntimeError means the library cannot carry out a call from where it was made. Most of these would otherwise wait on
themselves forever, so the library refuses them with a message naming the call and the fix.
A view's own work, re-entered.
reload()orload()from the view's ownon_load(), or from arebuild=ornav_rebuildhook during apush()orpop(), and two views whoseon_load()each reload the other.push(),pop(),replace(),send(),exit(), oron_timeout()from inside apush()orpop()of the same view (the new view'son_load()or a rebuild hook). A parent'sexit()orexit_children()is refused the same way from inside a navigation of a view attached to it.push(),pop(), orreplace()from inside the view's ownsend()(itson_pre_send(),on_load(), orseed_initial_state()).PaginatedRegion.show_page()before the host has rendered the region, or from inside the host'son_load(), whereset_page()is the call to make.
A view that is done.
send()on a view that has closed (exit(), a timeout,stop(), or an earlier send that failed or was refused), on one already being sent, or on one that handed its panel on (apush()orpop()from it, or a restart that restored the panel).push()orpop()on a view that has closed, andpush(),pop(), orreplace()on one that handed its panel on or that a failedpush()orpop()returned.push(view)orreplace(view)given an instance already sent, pushed, or closed.send()on a view built with neitherinteraction=norcontext=.
A paginator in the other mode. refresh_data() on a paginator not built by from_data(), and refresh_pages()
on one not built by from_cursor(). Each message names the call to make instead.
The store.
dispatch()from inside a reducer, or from a task a reducer started while it runs.- A middleware that returns without passing on one of the library's own records, such as
VIEW_CREATED, or passes it on under another type. The send that registers a view raises it. Once Discord has accepted the message, and during a close, it is logged instead (Short-Circuiting lists the records). undo()orredo()on a view whose store has noUndoMiddleware.- A
BatchContextentered a second time.
Modals.
open_modal()with a modal that already took a submission or timed out, since discord.py never takes a finished modal back. Build a new one for each open.Modal.submit()on a modal whoseon_submitoverride does not awaitsuper().on_submit(interaction), so the validators never ran and no verdict was recorded, and on an input whose value property has no storage behind it to write to, which means a discord.py release moved the attribute.
A wrapped callback. A callback under with_loading_state that answers through interaction.response, which the
loading state already used. Reply with self.respond() or interaction.followup.send().
Persistence.
- A backend used before
initialize()or afterclose(), and a raw-SQL transaction whose backend closed while it was open (nothing it wrote was committed). - A task started inside a
transaction()that opens one of its own while the outer one is open, and, on SQLite, a namespace write made inside the task's owntransaction(). SQLiteBackendon an SQLite that cannot turn on WAL journal mode.prune_unreachable()on a middleware built withoutbot=, andreattach()orprune_unreachable()from inside a running reattach pass or sweep, such as aREGISTRY_PRUNEDhook.flush_all()orclose()from a persistence hook (on_flush,on_error), andrehydrate()orprune_application(slot=)from an application hook, since each waits for the write the hook runs in. Start the call withasyncio.create_task()instead (see Observability).
Exception Classes¶
Seven classes, all importable from the package root:
Exception
├── InstanceLimitError
├── PersistenceError
│ ├── PersistenceConfigError
│ ├── PersistenceInitError
│ ├── PersistenceSchemaError
│ └── PersistenceRehydrateError
└── Warning
└── UserWarning
└── PrivateNameWarning
InstanceLimitError(view_type, limit, blocked_user_id=None, scope=None)¶
send() builds one when the view's instance_limit refuses it: under instance_policy = "reject" once the limit is
reached, and under "replace" when too few of the user's own views can be replaced (a view the user only takes part
in is not theirs to replace, and with protect_attached neither is one other users are attached to) or when one to
replace is a persistent panel and the new view is not. register_participant() builds one when the joining user
already fills the root class's limit, as the owner or a participant of other views.
Either way the error goes to on_instance_limit(), and the call reports the refusal
without raising: send() returns None and register_participant() returns False. The default hook replies with
instance_limit_message, or default_message when that is unset, on the view's interaction or command ctx (the
joiner's, when register_participant() is given their interaction). A refused player who is not the person reading
the reply, as when a send registers the players it lists, is named instead, with mentions off. The hook raises the
error only on a view with neither, such as one built with context=channel, and the error then reaches the caller of
send() or register_participant().
An override raises it to hand the refusal to its caller.
view_type(str): the class name of the view that was refusedlimit(int): the limit that was reachedblocked_user_id(int orNone): the joining user, for a refusal fromregister_participant().Nonefor one fromsend()scope(str orNone): theinstance_scopethe limit was counted under.Nonefor a refusal fromregister_participant()default_message(str, read-only): a rejection worded for who the limit counts: a joiner already taking part elsewhere, the server for"guild", everyone for"global", and otherwise the user. It names no class
Persistence Errors¶
"At setup" means inside setup_middleware(PersistenceMiddleware(...)), which runs the middleware's initialize().
| Class | Raised when |
|---|---|
PersistenceError |
Never raised itself. Catch it to handle any persistence failure |
PersistenceConfigError |
A namespace config (RegistryPersistence, ApplicationPersistence) or register_slot_policy() needs a capability the backend does not declare, such as a persistent slot policy with ttl_days on a backend without Capability.TTL_INDEX, or, at setup, a pending schema migration needs a backend declaring neither Capability.OPEN_ROWS nor Capability.RAW_SQL |
PersistenceInitError |
At setup, a backend's initialize() failed (the driver's error is its __cause__), or a PersistenceMiddleware() with no backend configured needs the optional aiosqlite, which is not installed |
PersistenceSchemaError |
At setup, the stored schema is newer than the library, a migration step has no migrator, a migrator raised, or renaming a table from its unprefixed name failed. A failed migrator or rename leaves the database as it was, and the step runs again on the next start |
PersistenceRehydrateError |
At setup, reading the registry or the application slots failed, or a stored slot payload is not valid JSON. A registry row that cannot be restored is not raised: it is skipped and listed under failed in last_reattach_summary |
from cascadeui import (
PersistenceError,
PersistenceMiddleware,
PersistenceSchemaError,
setup_middleware,
)
try:
await setup_middleware(PersistenceMiddleware(backend=backend))
except PersistenceSchemaError as exc:
# The stored schema is newer than this library: stop rather than write over it.
log.critical("Persistence schema too new: %s", exc)
raise
except PersistenceError as exc:
log.error("Persistence layer failed to initialize: %s", exc)
raise
Private Names¶
Names that start with an underscore belong to the class that defines them, and CascadeUI and discord.py call their
own. A class that defines one of the same name replaces what they call, which plain Python allows without a word.
When a class built on a library view, component, modal, composite, middleware, persistence backend,
PersistenceManager, StateStore, EmojiGrid, DevToolsCog, or testing stub is defined, the library compares each
such name with the one it replaces:
A replacement of one of the library's own methods in a shape the library could never call raises TypeError
instead:
- a value where it calls a method
- a method where it reads a value
- an
async defwhere it does not await - a signature that takes neither the method's required arguments alone nor all of its arguments
- a plain method where the library declares a classmethod, when it cannot take a call made on the class
Either message names the class, the name, and the base. Renaming the method is the fix.
The check reads the names each class body defines. A name an instance gets in __init__ (self._name = ...), an
annotation with no value (a dataclass field), or a name a metaclass or class decorator sets after the class is
created is not seen, and replaces the library's method as it does in plain Python.
A suite that replaces one on purpose filters the warning:
import warnings
from cascadeui import PrivateNameWarning
warnings.filterwarnings("ignore", category=PrivateNameWarning)
Discord Call Failures¶
DISCORD_CALL_ERRORS¶
The exceptions a Discord API call raises when the call itself fails, as a tuple for an except clause:
discord.HTTPException: Discord answered with an error statusdiscord.RateLimited: a rate limit would wait longer than the client'smax_ratelimit_timeout(raised only when the client sets one)aiohttp.ClientError: the request never reached Discord, such as a dropped connectionasyncio.TimeoutError: Discord never answered. discord.py sets no timeout of its own, so a request with no reply ends after aiohttp's five-minute default
The library catches with it wherever a failed call must not stop the work around it. The last three are siblings of
HTTPException, not subclasses, so except discord.HTTPException lets them escape.
from cascadeui import DISCORD_CALL_ERRORS
try:
await member.send("Your trial has started.")
except DISCORD_CALL_ERRORS as e:
logger.debug(f"Trial notice not delivered: {e}")
A programming error inside the same block (a NameError, an AttributeError) still raises, which a bare
except Exception would log as though the network had failed. An asyncio.wait_for or asyncio.timeout() expiry
inside the block is caught with the rest, so a block that handles its own timeout differently catches
asyncio.TimeoutError in a clause above this one. discord.InteractionResponded is not in the tuple: it means the
response slot is already used, which a caller answers with a followup (respond() does) rather than tolerates.
Raised or Logged¶
Some failures happen where no caller is waiting to receive them, so the library logs them instead. Where each one goes:
| Failure | What happens |
|---|---|
| A component callback raises | The view's on_error() runs: it logs the error with its traceback and answers the click with error_message |
A render from a state change raises (on_state_changed(), build_ui(), or the refresh it makes) |
Logged with its traceback. dispatch() does not raise it |
A post-event hook raises (on_page_changed, on_tab_switched, on_step_entered, on_step_exited, on_field_changed, on_replaced) |
Logged, and what fired it goes ahead |
refresh() or reload() meets a deleted message, a 429, a stalled edit, a dropped connection, or an expired ephemeral token |
Nothing is raised: the call returns a RenderOutcome, a deleted message closes the view, and a dropped connection also sets refresh_degraded. Any other Discord error, such as a 400 or a 403, is raised |
send() meets a Discord error |
The send rolls back, leaving no state and no live view, and the error is raised. A failure in the bookkeeping after the message is live is logged instead, and send() returns the message |
push() or pop() meets a Discord error |
The navigation rolls back, and the current view stays live on the message. A body Discord refused (code 50035) is then raised. Any other failure is not: the call returns the view it discarded, and Known Limitations lists the routes it tries first |
| A persistence write fails | Logged, reported to an on_error hook, and retried with backoff while the rows stay queued. After five failures in a row the retries pause until the next change. Nothing is raised into dispatch() |
Library logging is silent until a handler is attached, and setup_logging() attaches
one.