Files
xenia-pos-local/local_backend/core/errors.py
T
bonaminandClaude Opus 5.5 3eeafb565a feat(backend,waiter,terminal,manager): split the bill by amount
Owner 2026-11-23 (plan 6F.6). Venue setting payments.split_amount (off | two_equal | two_custom |
multiple_equal, each level with the ones before; default off) and payments.split_max_parts (10);
key ordering.payments.split_amount (everyone who takes payments; Alembic 0050 grants it).
POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status 'split': sold, no shift,
no payment method) and adds part lines (system product split_part, "Split bill 1/3", printed and
served; equal parts with the remainder on the last, or two parts with part 1 typed). Parts are paid
like any line (cash, card, tab). POST .../split-bills/{bill}/undo while no part is paid or tabbed.
Counting (services/sales.py): settled lines are the sales, parts never (a refunded part comes off
the settled lines by share); drawers and payment methods count the parts. Older reports use
split_bills.sold_filter / counts_as_sale. Locks: parts can't be cancelled, moved, combined or
re-priced; settled lines are no longer active; closing or cancelling an order with unpaid parts is
refused. Fiscal: one receipt with the settled lines when the last part is paid, with each method's
amount (txt driver: CD per card amount, then CR for cash).
Waiter: Pay -> "Split the amount" (pre-filled from the customers), the split bill above the lines
with Undo. Counter: "By amount" in the payment (quick sale split and paid at once, Q-4; a table's
lines split then paid). Manager: the pay dialog splits, the order shows its split bills, Settings ->
Operation card. Shared rules in @xenia/ordering/split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:57:54 +02:00

387 lines
27 KiB
Python

"""API errors as stable codes (APPS_PLATFORM D-12, §3.2).
Every error response has this shape:
{"error": {"code": "order.not_found", "params": {"order_id": 7}, "message": "Order 7 not found."},
"detail": "Order 7 not found."}
- code: stable identifier; frontends translate it (i18n key `errors.<code>`).
- params: values the translated text can use.
- message: English, for logs, curl and un-migrated screens.
- detail: kept for frontends written before v2 (they read `detail`).
New and converted code raises XeniaError:
raise XeniaError("order.not_found", order_id=order_id)
The status comes from the registry below; pass status= only to override it.
Plain HTTPException is wrapped as code "http.<status>" with its original `detail` untouched
(the routers have none since step 6.1; tests/test_errors.py refuses new ones).
Request validation errors become "validation.invalid" with the field errors in params.
Unhandled exceptions become "internal.error" (500) with the request id in params.
Agent notes:
- Add every new code to CODES with its HTTP status and English message (str.format
placeholders from params). tests/test_errors.py fails on a raised code that
isn't registered (via XeniaError's constructor).
- Codes are part of the API contract: never rename one; add a new one instead.
"""
from __future__ import annotations
import logging
from http import HTTPStatus
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
logger = logging.getLogger("xenia.errors")
# code -> (HTTP status, English message)
CODES: dict[str, tuple[int, str]] = {
# access / licensing / modules (filled in by steps 1.3-1.9)
"access.denied": (403, "You don't have permission to do this ({key})."),
"access.override_possible": (403, "A manager can approve this ({key})."),
"access.override_invalid": (403, "This approval isn't valid any more. Ask a manager again."),
"access.not_overridable": (422, "{key} can't be approved by a manager."),
"access.approver_lacks_key": (403, "That account can't approve this ({key})."),
"access.override_rate_limited": (429, "Too many wrong PINs. Wait a few minutes and try again."),
"access.unknown_key": (422, "There is no permission {key}."),
"access.cannot_grant": (403, "You can only give permissions you have yourself ({key})."),
"module.disabled": (403, "The {module} module is turned off."),
"module.not_licensed": (402, "This site's license doesn't include {module}."),
"module.unknown": (404, "There is no module {module}."),
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
"license.limit_reached": (402, "License limit reached for {module} {limit} ({max})."),
"license.expired": (402, "The license has expired."),
"license.history_limited": (402, "This license shows only the last {days} days of history ({module})."),
# identity
"auth.invalid_credentials": (401, "Wrong username or password."),
"auth.session_ended": (401, "Your session has ended. Please log in again."),
"auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."),
"auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."),
"auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."),
"auth.username_required": (422, "Enter your username."),
"auth.client_not_allowed": (403, "This account can't use the {client} app."),
"auth.session_not_found": (404, "Session not found."),
"auth.wrong_pin": (401, "Wrong PIN. {attempts_left} tries left before you are signed out."),
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
"pos.shift_required": (409, "Start your shift before selling."),
"pos.payment_invalid": (422, "This payment doesn't add up ({reason})."),
"pos.fiscal_vat_missing": (422, "Fiscal receipts are on, but these products have no VAT group: {names}."),
"pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."),
"pos.table_not_found": (404, "Table {table_id} not found."),
"pos.table_not_yours": (403, "{table} isn't in your zones. A manager can add the zone to your account."),
"pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."),
"pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."),
"order.items_not_combinable": (422, "These lines can't be combined: only unpaid lines of the same item, with the same choices, note, price and kitchen state, and no discount, deal or tab."),
"order.not_sold_here": (422, "{name} isn't sold for this kind of order."),
"order.lines_required": (422, "This app sent the order in an old format. Update the app and send it again."),
"order.line.product_unavailable": (422, "{name} isn't available any more (line {line})."),
"order.line.option_gone": (422, "{name}: a chosen option doesn't exist any more (line {line}). Remove it and add it again."),
"order.line.choice_missing": (422, "{name}: a required choice is missing (line {line})."),
"order.line.quantity": (422, "{name}: that quantity isn't allowed (line {line})."),
"order.line.price": (422, "{name}: that price change isn't allowed (line {line})."),
"order.line.client_price": (422, "{name}: the app sent its own prices, but prices come from the server (line {line}). Update the app."),
"fees.area_not_found": (404, "Delivery area {area_id} not found."),
"fees.rule_not_found": (404, "Fee rule {rule_id} not found."),
"fees.area_in_use": (409, "This area is used by fee rules: {rules}. Change those rules first."),
"fees.order_invalid": (422, "The new order must list every rule once."),
"fees.vat_group_unknown": (422, "VAT group {vat_group_id} isn't one of the fiscal machine's groups."),
"refund.invalid": (422, "This refund doesn't add up ({reason})."),
"refund.too_old": (409, "Only payments from today's business day can be refunded at the counter."),
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
"online.not_found": (404, "Online order {order_id} not found."),
"online.status_changed": (409, "This online order was changed on another screen in the meantime. Check where it is now."),
"caller_id.key_invalid": (403, "The phone system's key is missing or wrong."),
"display.qr_url_missing": (422, "Enter the link the QR code opens."),
"display.look_unknown": (404, "Look {look_id} not found."),
"display.look_default": (409, "The default look can't be deleted. Make another look the default first."),
"display.not_a_display": (404, "Device {device_id} isn't a customer display."),
"media.not_found": (404, "File {media_id} isn't in the media library."),
"media.type": (422, "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4, MOV or WebM)."),
"media.too_big": (413, "The file is too big (at most {max_mb} MB)."),
"media.too_many_pixels": (422, "The picture is too large (at most {max_mp} megapixels)."),
"media.unreadable": (422, "This picture can't be read. Save it again as JPG or PNG and upload it."),
"media.in_use": (409, "This file is used by {uses}. Remove it there first."),
"media.not_a_picture": (422, "Pick a picture here, not a video."),
"signage.playlist_unknown": (404, "Playlist {playlist_id} not found."),
"signage.slide_unknown": (404, "Slide {slide_id} not found."),
"signage.not_a_screen": (404, "Device {device_id} isn't a signage screen."),
"signage.schedule_unknown": (404, "Schedule {schedule_id} not found."),
"signage.not_a_video": (422, "Pick a video for this slide."),
"signage.too_many_widgets": (422, "A slide holds at most {max} widgets (Signage → Message & settings → Performance)."),
"signage.content_invalid": (422, "This slide's setting isn't valid ({field}: {reason})."),
"signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."),
"signage.weather_offline": (503, "The weather service can't be reached: the venue's server needs internet for it."),
"menu_tablet.no_table": (409, "This tablet isn't at a table, so it can't call a waiter."),
"menu_tablet.call_too_soon": (429, "A waiter was just called. Try again in {seconds} seconds."),
"menu_tablet.no_ordering": (409, "Ordering isn't on for this tablet."),
"menu_tablet.too_many": (422, "At most {most} items in one order."),
"menu_tablet.too_many_of": (422, "At most {most} of \"{name}\" in one order."),
"menu_tablet.too_soon": (429, "An order was just sent. Try again in {seconds} seconds."),
"menu_tablet.table_closed": (409, "Please ask a waiter to open your table first."),
"menu_tablet.day_closed": (409, "The venue isn't taking orders right now. Please ask a waiter."),
"menu_tablet.no_staff": (409, "There is no staff account to place the order with."),
"menu_tablet.order_not_found": (404, "This order was not found."),
"menu_tablet.order_answered": (409, "This order was already answered."),
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
"media.folder_unknown": (404, "That folder isn't in the media library any more."),
"reservation.not_found": (404, "Booking {reservation_id} not found."),
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
"reservation.table_unknown": (404, "Table {table_id} not found."),
"reservation.table_kept": (409, "That table is already kept for {name} at {time}."),
"reservation.table_busy": (409, "That table already has an open order. Pick another table, or close that order first."),
"kds.item_not_found": (404, "Item {item_id} not found on this order."),
"kds.item_claimed": (409, "{name} is already on this item."),
"kds.claim_needs_staff": (403, "Only a staff member can claim an item."),
"device.revoked": (401, "This device was removed. Pair it again."),
"device.not_paired": (401, "This device isn't paired with the venue."),
"device.out_of_scope": (403, "A {app} device can't do this ({key})."),
"device.required": (401, "This login belongs to a paired device. Use it from that device."),
"device.not_found": (404, "Device {device_id} not found."),
"device.pair_code_invalid": (404, "That pairing code is wrong or has expired."),
"device.pair_rate_limited": (429, "Too many pairing requests. Wait a few minutes and try again."),
"device.not_an_app": (422, "{app} is not an app that runs on a device."),
"device.login_mode_invalid": (422, "A {app} device can't use the login mode {mode}."),
"device.link_invalid": (422, "Device {device_id} can't be linked to this device."),
# validation
"validation.invalid": (422, "Some fields are invalid."),
"validation.unknown_language": (422, "Unsupported language: {language}."),
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
"validation.device_config": (422, "This device setting is not valid: {key}."),
# server
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
# domain
"order.not_found": (404, "Order {order_id} not found."),
"notification.not_found": (404, "Notification {notification_id} not found."),
"system.log_not_found": (404, "There is no log file for {date}."),
"catalog.unknown_category": (422, "There is no category {category_id}."),
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
"catalog.allergen": (422, "Unknown allergen or level: {allergen}."),
"catalog.translation": (422, "The menu can't be translated like that: {what}."),
# converted from HTTPException (plan step 6.1)
"auth.password_current_required": (400, "Enter your current password to set a new one."),
"auth.no_password": (400, "This account has no password yet."),
"auth.password_wrong": (400, "The current password is wrong."),
"auth.password_too_short": (400, "The password must be at least {min} characters long."),
"auth.pin_too_short": (400, "The PIN must be at least {min} digits long."),
"license.locked": (423, "The system was locked by the administrator. Contact support."),
"settings.invalid_json": (422, "The settings must be valid JSON."),
"settings.unknown_key": (400, "There is no setting {key}."),
"business_day.already_open": (400, "A business day is already open."),
"business_day.none_open": (404, "No business day is open."),
"business_day.closed": (403, "The venue isn't open: a manager must open the business day first."),
"business_day.orders_open": (409, "{open_orders} table(s) still open, {partially_paid} with unpaid items."),
"business_day.not_found": (404, "Business day not found."),
"business_day.not_closed": (400, "Only a closed business day can be edited."),
"business_day.close_in_future": (400, "The closing time can't be in the future."),
"business_day.close_before_last_order": (400, "The closing time can't be earlier than the last order's close ({time})."),
"business_day.delete_open": (400, "An open business day can't be deleted. Close it first."),
"business_day.has_shifts": (409, "This business day has {count} shift(s). Delete those first."),
"validation.datetime": (422, "That date or time isn't valid."),
"validation.choice": (400, "{field} can't be {value}."),
"validation.range": (400, "{field} must be between {min} and {max}."),
"validation.positive": (400, "{field} must be more than zero."),
"validation.missing": (400, "{field} is required."),
"validation.lan_ip": (422, "Enter a local network IPv4 address (e.g. 192.168.1.50 or 10.0.0.5)."),
"chat.not_found": (404, "Conversation not found."),
"chat.not_participant": (403, "You're not in this conversation."),
"chat.empty_message": (400, "The message is empty."),
"chat.system_group": (403, "You can't leave the staff group."),
"chat.leave_direct": (400, "A one-to-one conversation can't be left."),
"chat.direct_two": (400, "A one-to-one conversation has exactly two people."),
"chat.group_name": (400, "A group conversation needs a name."),
"customer.not_found": (404, "Customer not found."),
"transfer.wrong_type": (400, "This file isn't a {expected} export."),
"transfer.version": (400, "This export's version isn't supported."),
"contact.not_found": (404, "Contact not found."),
"expense.not_found": (404, "Expense not found."),
"expense.over_due": (400, "That's more than what is still due ({due})."),
"expense.below_paid": (400, "{paid} has been paid already: the total can't be less."),
"expense.document_not_found": (404, "Document not found."),
"channel_price.not_found": (404, "Channel price not found."),
"channel_price.set_one_product": (400, "A set price is for one product: pick one product (and no categories), or change the price by an amount or a percentage."),
"scene.not_found": (404, "Scene {scene_id} not found."),
"scene.until_past": (400, "That time has already passed: pick a later one."),
"signage.scene_unknown": (404, "Scene {scene_id} not found."),
"signage.screen_unknown": (404, "Screen {device_id} not found."),
"expense.document_type": (422, "Upload a PDF or a photo (JPG, PNG, WebP or HEIC)."),
"expense.document_too_big": (413, "The file is too big (at most {max_mb} MB)."),
"flag.not_found": (404, "Mark not found."),
"flag.in_use": (409, "This mark is on {count} table(s). Remove it there first."),
"flag.invalid_ids": (400, "Some of these marks don't exist."),
"staff_message.template_not_found": (404, "Message template not found."),
"staff_message.not_found": (404, "Message not found."),
"note.not_found": (404, "Note not found."),
"todo.not_found": (404, "To-do not found."),
"order.not_yours": (403, "This order isn't one of your tables."),
"order.not_open": (400, "This order isn't open any more."),
"order.item_not_found": (404, "That item isn't on the order any more."),
"order.item_paid": (400, "This item is already paid."),
"order.item_not_active": (400, "Only items still on the order can be changed."),
"order.price_change_off": (403, "Changing prices by hand is turned off for this venue."),
"order.one_more_off": (400, "\"One more\" isn't turned on for this product."),
"order.one_more_line": (400, "This line can't be ordered again with one tap."),
"order.quantity_change_off": (403, "Changing quantities is turned off for this venue."),
"order.quantity_remove_off": (403, "Quantities can only go up at this venue."),
"order.quantity_invalid": (400, "Choose a whole number from 1 to {max}."),
"order.quantity_line": (400, "This line's quantity can't be changed here."),
"order.price_change_sent_off": (403, "Prices can only be changed before the items are sent."),
"order.price_reason_required": (400, "Say why the price changes."),
"split.not_allowed": (403, "Splitting a bill this way isn't turned on for this venue."),
"split.lines_changed": (409, "Some of these items were paid or changed meanwhile. Look again."),
"split.amount_invalid": (400, "Each part must be more than 0 and less than the total ({total})."),
"split.part_locked": (400, "This is part of a split bill: undo the split to change it."),
"split.not_found": (404, "That split bill isn't there any more."),
"split.paid_already": (409, "A part is already paid or on a tab: the split can't be undone."),
"split.parts_unpaid": (400, "Parts of a split bill are still unpaid: take their payment first."),
"order.nothing_paid": (404, "There are no paid items to undo."),
"order.cannot_close": (400, "This order can't be closed now ({status})."),
"order.no_active_items": (400, "None of these items are on the order any more."),
"order.waiter_assigned": (400, "That waiter is already on this order."),
"order.assignment_not_found": (404, "That waiter isn't on this order."),
"order.same_table": (400, "The order is already on that table."),
"order.same_order": (400, "An order can't be joined with itself."),
"order.target_not_found": (404, "The other order isn't there any more."),
"order.split_quantity": (400, "Split into 1 to {max} pieces."),
"order.discounts_off": (403, "Discounts are turned off for this venue."),
"order.no_customer": (400, "Give the order a customer first."),
"order.item_not_tabbable": (400, "This item is already {status}: it can't go on a tab."),
"order.product_unavailable": (400, "Product {product_id} isn't available."),
"printer.not_found": (404, "That printer isn't there or is turned off."),
"print_job.not_found": (404, "That print job isn't there any more."),
"print_job.not_pending": (400, "Only tickets still waiting to print can be cancelled."),
"print_job.done": (409, "That ticket isn't waiting any more: it was printed or dealt with on another screen."),
"print.printer_off": (409, "The printer {printer} is turned off in the settings."),
"print.redirect_failed": (502, "{printer} didn't print it either ({error}). The ticket is still waiting."),
"table.not_found": (404, "Table not found."),
"floor_plan.not_found": (404, "Floor plan not found."),
"floor_plan.bad_outline": (422, "The floor's shape needs 3 to 100 corners, all inside the plan."),
"floor_plan.bad_zone": (422, "That zone no longer exists."),
"floor_plan.bad_background": (422, "The background must be a picture from the media library."),
"floor_plan.bad_layout": (422, "The layout has a table twice or a place that is not a number."),
"table.busy": (400, "That table already has an open order."),
"table.has_order": (400, "A table with an open order can't be deleted or turned off."),
"table.name_too_long": (400, "The table names would be too long ({name}: at most {max} characters). Shorten the prefix or make fewer."),
"table_group.name_taken": (400, "There is already a group with that name."),
"table_group.not_found": (404, "Table group not found."),
"prep_zone.not_found": (404, "Prep zone not found."),
"price_group.not_found": (404, "Price group not found."),
"modifier.not_found": (404, "Price rule not found."),
"deal.not_found": (404, "Deal not found."),
"pricing.bad_condition": (422, "A condition is incomplete: fill in all its values."),
"pricing.bad_limit": (422, "A discount limit must be a number of 0 or more, or empty for no limit."),
"catalog.category_not_found": (404, "Category not found."),
"catalog.parent_not_found": (404, "The parent category doesn't exist."),
"catalog.nest_has_children": (400, "A category with sub-categories can't go under another one."),
"catalog.too_deep": (400, "Categories go at most two levels deep."),
"catalog.own_parent": (400, "A category can't be its own parent."),
"catalog.group_not_found": (404, "Option group not found."),
"product.not_found": (404, "Product not found."),
"product.in_past_orders": (400, "This product is in past orders, so it can't be deleted. Archive it instead."),
"staff.not_found": (404, "Staff member not found."),
"staff.username_taken": (409, "That username is already taken."),
"staff.superadmin_protected": (403, "A superadmin account can't be changed."),
"staff.superadmin_only": (403, "Only a superadmin can give the superadmin role."),
"staff.role_invalid": (400, "There is no role {role}."),
"staff.avatar_type": (400, "The photo must be a picture file."),
"staff.assignment_exists": (400, "That assignment already exists."),
"staff.pin_invalid": (422, "A PIN is {min} to {max} digits."),
"staff.username_needed": (422, "Every person needs a username."),
"staff.password_own": (409, "Change your own password from your profile."),
"staff.delete_self": (409, "You can't delete yourself."),
"staff.has_history": (409, "{name} has orders or shifts on record, so they can't be deleted. Block them instead: they can't sign in, and the reports keep their name."),
"staff.assignment_not_found": (404, "Assignment not found."),
"schedule.shift_not_found": (404, "Scheduled shift not found."),
"schedule.bad_time": (422, "Times are written like 09:30."),
"schedule.overlap": (409, "{name} already has a shift from {start} to {end} that day."),
"setup.done": (409, "Setup is already done: a manager account exists."),
"shift.already_active": (400, "This person already has a shift going."),
"shift.start_needs_manager": (403, "Starting the shift needs a manager's approval."),
"shift.end_needs_manager": (403, "Ending the shift needs a manager's approval."),
"shift.others_need_manager": (403, "Only managers can start shifts for other staff."),
"shift.none_active": (404, "No shift is going."),
"shift.not_found": (404, "Shift not found."),
"shift.not_yours": (403, "This shift belongs to someone else."),
"shift.ended": (400, "This shift has already ended."),
"shift.on_break": (400, "A break is already going."),
"shift.no_break": (404, "No break is going."),
"shift.delete_active": (400, "A shift that is still going can't be deleted. End it first."),
"tab.not_found": (404, "Tab not found."),
"tab.already_open": (400, "This customer already has an open tab."),
"tab.over_balance": (400, "That's more than the balance ({balance})."),
"tab.has_balance": (400, "The tab still owes {balance}. Pay it or forgive it first."),
"waste.not_found": (404, "Throwaway entry not found."),
"waste.not_today": (403, "Only throwaways of the open business day can be deleted."),
}
class XeniaError(Exception):
"""An API error with a registered code. raise XeniaError("order.not_found", order_id=5)."""
def __init__(self, code: str, status: int | None = None, **params):
if code not in CODES:
raise KeyError(f"unregistered error code {code!r}: add it to core/errors.py CODES")
default_status, template = CODES[code]
self.code = code
self.status = status or default_status
self.params = params
try:
self.message = template.format(**params)
except (KeyError, IndexError):
self.message = template
super().__init__(self.message)
def error_body(code: str, message: str, params: dict | None = None, detail=None) -> dict:
return {"error": {"code": code, "params": params or {}, "message": message},
"detail": message if detail is None else detail}
async def _xenia_error_handler(request: Request, exc: XeniaError):
return JSONResponse(error_body(exc.code, exc.message, exc.params), status_code=exc.status)
async def _http_exception_handler(request: Request, exc: StarletteHTTPException):
detail = exc.detail
if isinstance(detail, str):
message = detail
elif isinstance(detail, dict) and isinstance(detail.get("message"), str):
message = detail["message"]
else:
try:
message = HTTPStatus(exc.status_code).phrase
except ValueError:
message = "Error"
return JSONResponse(error_body(f"http.{exc.status_code}", message, detail=detail),
status_code=exc.status_code, headers=getattr(exc, "headers", None))
async def _validation_handler(request: Request, exc: RequestValidationError):
errors = [{"field": ".".join(str(p) for p in e.get("loc", ())[1:]) or None,
"type": e.get("type"), "message": e.get("msg")} for e in exc.errors()]
# `detail` stays FastAPI's usual list, so existing frontends keep working
return JSONResponse(error_body("validation.invalid", CODES["validation.invalid"][1],
{"errors": jsonable_encoder(errors)}, detail=jsonable_encoder(exc.errors())),
status_code=422)
async def _unhandled_handler(request: Request, exc: Exception):
"""Last resort: a bug. Logged with the traceback; the client gets the request id
(also in the X-Request-ID header) so support can find the log lines."""
from core.logging import current_request_id
rid = getattr(request.state, "request_id", None) or current_request_id() or "-"
logger.exception("http.unhandled_error request_id=%s path=%s", rid, request.url.path)
err = XeniaError("internal.error", request_id=rid)
return JSONResponse(error_body(err.code, err.message, err.params), status_code=500,
headers={"X-Request-ID": rid})
def install_error_handlers(app: FastAPI) -> None:
app.add_exception_handler(Exception, _unhandled_handler)
app.add_exception_handler(XeniaError, _xenia_error_handler)
app.add_exception_handler(StarletteHTTPException, _http_exception_handler)
app.add_exception_handler(RequestValidationError, _validation_handler)