frappex-client v0.1.1

Going further

Errors#

Every exception frappex-client raises derives from FrappexError, so one except clause can catch all of them, and each kind of failure has its own class so you can react to it specifically.

FrappexError
├── ConfigurationError        a bad or unsafe argument; nothing was sent
├── TransportError            no HTTP response arrived
│   └── RequestTimeoutError
├── ResponseTooLargeError     the body exceeded the size limit
├── UnexpectedResponseError   a redirect or a reply that is not Frappe JSON
└── APIError                  the site answered with an error
    ├── AuthenticationError   401
    ├── PermissionDeniedError 403
    ├── NotFoundError         404
    ├── ConflictError         409
    ├── ValidationError       417 and other 4xx
    ├── RateLimitError        429
    └── ServerError           5xx

Which exception, when#

Exception Typical cause What to do
AuthenticationError Wrong, revoked or expired key, token or password Check the credentials; do not retry blindly
PermissionDeniedError The user lacks a role, or a guest called a protected route Grant the role, or use another user
NotFoundError The document, DocType or method does not exist Often expected: treat as "missing"
ConflictError A duplicate name or unique value Look up the existing record instead
ValidationError A mandatory field is missing, a value is invalid, a link is broken Read server_messages and fix the data
RateLimitError Too many requests Wait retry_after seconds; frappex-client already retried short waits
ServerError An exception inside the site Check the site's Error Log
TransportError DNS, TLS or connection failure Retry later; for writes, check first
RequestTimeoutError The site took longer than the timeout Raise the timeout or make the query cheaper
UnexpectedResponseError base_url points at a proxy, login page or redirect Fix the address
ResponseTooLargeError The reply exceeded max_response_bytes Page the query, or stream files with download_to
ConfigurationError http:// without opt-in, verify=False, a .. name Fix the argument

Catching errors#

Catch the specific case you can handle, and let the rest propagate:

from frappex_client import ConflictError, FrappexError, NotFoundError, ValidationError

try:
    customer = client.get_doc("Customer", name)
except NotFoundError:
    customer = client.insert("Customer", {"customer_name": name})

try:
    client.insert("Customer", {"customer_name": "Acme", "customer_group": "Retail"})
except ConflictError:
    pass  # it already exists
except ValidationError as error:
    log.warning("Customer rejected: %s", "; ".join(error.server_messages))
except FrappexError:
    log.exception("ERP call failed")
    raise

What an APIError carries#

Attribute Example Meaning
status_code 417 HTTP status of the reply
exc_type "MandatoryError" The server's exception class, when reported
server_messages ("Value missing for Customer: Customer Group",) Messages from frappe.throw and friends
traceback "Traceback (most recent call last): ..." The server traceback, only if the site exposes it
retry_after 12.0 RateLimitError only: advised wait in seconds

str(error) gives a one-line summary: the status and the first server message.

try:
    client.insert("Customer", {"customer_name": "Acme"})
except ValidationError as error:
    print(error.status_code, error.exc_type)
    for message in error.server_messages:
        print("-", message)

Frappe 14

Frappe 14 does not always report the exception class, so exc_type can be None there. Rely on the exception class (NotFoundError, and so on), which is decided by the HTTP status and works on every version.

Server messages can contain HTML#

Frappe messages are written for the desk and often contain markup such as <strong> or links. If you show server_messages in a web page, escape them first: they can include text other users typed.

import html

safe = [html.escape(message) for message in error.server_messages]

The traceback is kept out of logs#

A server traceback can reveal file paths, SQL and data. frappex-client stores it on error.traceback for debugging but never puts it in str(error), so logging the exception does not leak it. Most production sites do not send tracebacks at all.

Network errors and writes#

When a TransportError interrupts an insert, update or POST call, the site may or may not have applied it. frappex-client never retries writes for that reason. See Why writes are never retried for how to recover safely.

Found a mistake? Open an issue.