Error Handling
Relevant source files
The following files were used as context for generating this wiki page:
The MBBank library implements a structured error handling system designed to manage various failure states, including API-level errors, internal library exceptions, and external service failures. The system differentiates between standard API responses that indicate failure and protocol-level issues such as missing security headers or CAPTCHA resolution failures.
Error handling is integrated directly into the request-response cycle of both sync and async clients. When the MBBank API returns a non-zero response code or an invalid status, the library maps these into specific exception classes to allow developers to implement granular try-except blocks.
Sources: mbbank/errors.py:1-65, mbbank/sync/mbbank.py:84-118
Exception Hierarchy
The library defines a custom exception hierarchy to categorize different types of failures encountered during interaction with MBBank's services.
The diagram above shows the relationship between custom exception classes used in the project.
Sources: mbbank/errors.py:7-65
Custom Exception Types
| Exception Class | Description | Attributes |
|---|---|---|
MBBankAPIError | Raised when the MBBank API returns an error response code. | code, message |
MBBankError | Internal library error exception for logic failures. | err_out |
CapchaError | Raised when CAPTCHA processing fails or exceeds retry limits. | err_out |
BankNotFoundError | Raised when a specified bank or card bank cannot be found. | err_out |
CryptoVerifyError | Raised when the API requires crypto verification (Status 428). | resp_out, content_type |
Sources: mbbank/errors.py:7-65
API Error Resolution
The MBBankAPIError class includes a mechanism to provide human-readable messages for specific error codes that may not have descriptive messages in the raw API response.
custom_messages = {"MC3011": "Card not found."}
class MBBankAPIError(Exception):
def __init__(self, err_out):
self.code = err_out["responseCode"]
if self.code in custom_messages.keys():
self.message = custom_messages[self.code]
else:
self.message = err_out["message"]
super().__init__(f"{self.code} | {self.message}")
Sources: mbbank/errors.py:1-24
Authentication and Retry Logic
The library handles specific API error codes automatically during the authentication flow. For instance, the error code GW283 is treated as a transient CAPTCHA error, triggering a retry attempt until the retry_times limit is reached.
The flow diagram illustrates how the library manages CAPTCHA failures and authentication retries.
Sources: mbbank/sync/mbbank.py:173-193, mbbank/aio/mbbank.py:157-177
Request Lifecycle Error Handling
During a standard request via _req, the library monitors for session expiration and security requirements.
- Session Expiration: If the API returns response code
GW200, the library automatically calls_authenticate()to refresh the session and retries the request. - Missing Result: If
data_out["result"]is None, it triggers agetBalance()call to verify session state. - Crypto Verification: If the server returns a
428status code, aCryptoVerifyErroris raised, indicating that advanced cryptographic verification is required by the webapp.
Sources: mbbank/sync/mbbank.py:93-117, mbbank/aio/mbbank.py:195-224
External Service Errors
Some modules interact with external MBBank microservices (e.g., mbcardgw). These services use a different error structure encapsulated in an ErrorInfo modal.
| Field | Type | Description |
|---|---|---|
code | str | The external service error code (e.g., "000" for success). |
message | str | The error message from the external service. |
target | Optional[Any] | The target component of the error. |
When interacting with ATM card services, the library checks the errorInfo.code. If it is not "000", it wraps the result in an MBBankAPIError.
Sources: mbbank/modals/external_service.py:5-14, mbbank/sync/mbbank.py:417-423
Transfer Context Validation
The TransferContext (and its async counterpart) implements pre-flight checks before executing transactions. It raises MBBankError if methods are called out of sequence (e.g., attempting a transfer before generating a QR code or starting the context).
- Bank Validation: If a provided
bank_codeis not found in the cached bank list, aBankNotFoundErroris raised. - State Validation: Methods like
verify_transferortransfercheck for the existence ofbankandto_account_nameobjects before proceeding.
Sources: mbbank/sync/transfer.py:75-156, mbbank/base/transfer.py:76-83
Summary
Error handling in the MBBank library is a multi-layered system that covers CAPTCHA retries, automatic session re-authentication, and specific exception mapping for API failures. By categorizing errors into specialized classes like MBBankAPIError and CryptoVerifyError, the library provides clear signals to the consumer regarding the nature of the failure, whether it be a protocol requirement or a business logic error from the bank's backend.