from __future__ import annotations from collections.abc import Mapping from dataclasses import dataclass from enum import StrEnum from http import HTTPStatus from typing import Literal class ErrorCode(StrEnum): UNKNOWN_TOOL = "unknown_tool" UNSUPPORTED_FILE_TYPE = "unsupported_file_type" UNSAFE_FILE_NAME = "unsafe_file_name" DUPLICATE_FILE = "duplicate_file" TOO_MANY_FILES = "too_many_files" TOO_FEW_FILES = "too_few_files" FILE_TOO_LARGE = "file_too_large" INVALID_OPTIONS = "invalid_options" INVALID_INPUT = "invalid_input" INVALID_REQUEST = "invalid_request" UNREADABLE_FILE = "unreadable_file" UNPROCESSED_FILE = "unprocessed_file" PASSWORD_REQUIRED = "password_required" # noqa: S105 An error code. WRONG_PASSWORD = "wrong_password" # noqa: S105 An error code. MAPPING_REQUIRED = "mapping_required" INVALID_MAPPING = "invalid_mapping" OCR_REQUIRED = "ocr_required" UNSUPPORTED_LAYOUT = "unsupported_layout" NO_RECORDS = "no_records" UNAUTHENTICATED = "unauthenticated" JOB_NOT_FOUND = "job_not_found" JOB_EXPIRED = "job_expired" JOB_STATE_CONFLICT = "job_state_conflict" SERVER_BUSY = "server_busy" TIMEOUT = "timeout" INTERNAL_ERROR = "internal_error" @dataclass(frozen=True) class ErrorSpec: status: HTTPStatus message: str ERRORS: Mapping[ErrorCode, ErrorSpec] = { ErrorCode.UNKNOWN_TOOL: ErrorSpec(HTTPStatus.NOT_FOUND, "There is no such tool."), ErrorCode.UNSUPPORTED_FILE_TYPE: ErrorSpec( HTTPStatus.UNSUPPORTED_MEDIA_TYPE, "This tool does not accept this type of file." ), ErrorCode.UNSAFE_FILE_NAME: ErrorSpec( HTTPStatus.BAD_REQUEST, "The file name is not allowed. Rename the file and try again." ), ErrorCode.DUPLICATE_FILE: ErrorSpec( HTTPStatus.CONFLICT, "A file with this name is already in the job." ), ErrorCode.TOO_MANY_FILES: ErrorSpec( HTTPStatus.BAD_REQUEST, "Too many files for this tool. Remove some and start again." ), ErrorCode.TOO_FEW_FILES: ErrorSpec( HTTPStatus.BAD_REQUEST, "This tool needs more files. Add them and start again." ), ErrorCode.FILE_TOO_LARGE: ErrorSpec( HTTPStatus.REQUEST_ENTITY_TOO_LARGE, "The file is larger than the upload limit." ), ErrorCode.INVALID_OPTIONS: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "Some details are not valid. Correct them and start again." ), ErrorCode.INVALID_INPUT: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "The file does not hold what this tool expects. Check the file.", ), ErrorCode.INVALID_REQUEST: ErrorSpec( HTTPStatus.BAD_REQUEST, "The request was not understood. Refresh the page and try again." ), ErrorCode.UNREADABLE_FILE: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "The file could not be opened. Upload a fresh copy." ), ErrorCode.UNPROCESSED_FILE: ErrorSpec( HTTPStatus.INTERNAL_SERVER_ERROR, "Something went wrong on the server while reading this file. Try again.", ), ErrorCode.PASSWORD_REQUIRED: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "The PDF is password protected. Enter its password to continue.", ), ErrorCode.WRONG_PASSWORD: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "That password did not open the PDF. Check it and try again.", ), ErrorCode.MAPPING_REQUIRED: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "Check how the registers' columns are read, then continue.", ), ErrorCode.INVALID_MAPPING: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "The column choices do not match the sheets the job asked about. Refresh and try again.", ), ErrorCode.OCR_REQUIRED: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "The page is a scanned image and could not be read. " "Upload a clearer scan or the digital statement.", ), ErrorCode.UNSUPPORTED_LAYOUT: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "This statement layout is not supported. " "Upload the statement as downloaded from the bank or the portal.", ), ErrorCode.NO_RECORDS: ErrorSpec( HTTPStatus.UNPROCESSABLE_ENTITY, "No entries were found in the file. Check that it is the right one.", ), ErrorCode.UNAUTHENTICATED: ErrorSpec( HTTPStatus.UNAUTHORIZED, "Your sign-in has ended. Sign in again to continue." ), ErrorCode.JOB_NOT_FOUND: ErrorSpec( HTTPStatus.NOT_FOUND, "This job does not exist. Start a new one." ), ErrorCode.JOB_EXPIRED: ErrorSpec( HTTPStatus.GONE, "The files for this job were deleted after the time limit." ), ErrorCode.JOB_STATE_CONFLICT: ErrorSpec( HTTPStatus.CONFLICT, "The job cannot do that right now. Refresh to see where it is." ), ErrorCode.SERVER_BUSY: ErrorSpec( HTTPStatus.SERVICE_UNAVAILABLE, "The server is busy with other jobs. Try again in a few minutes.", ), ErrorCode.TIMEOUT: ErrorSpec( HTTPStatus.GATEWAY_TIMEOUT, "The job took too long and was stopped. Try again with fewer files.", ), ErrorCode.INTERNAL_ERROR: ErrorSpec( HTTPStatus.INTERNAL_SERVER_ERROR, "Something went wrong on the server. Try again." ), } PasswordReason = Literal[ErrorCode.PASSWORD_REQUIRED, ErrorCode.WRONG_PASSWORD] ADAPTER_CODES = frozenset( { ErrorCode.TOO_FEW_FILES, ErrorCode.INVALID_OPTIONS, ErrorCode.INVALID_INPUT, ErrorCode.UNREADABLE_FILE, ErrorCode.UNPROCESSED_FILE, ErrorCode.OCR_REQUIRED, ErrorCode.UNSUPPORTED_LAYOUT, ErrorCode.NO_RECORDS, ErrorCode.INVALID_MAPPING, } ) class CodedError(Exception): def __init__( self, code: ErrorCode, file: str | None = None, page: int | None = None, detail: str | None = None, ) -> None: if file == "": raise ValueError("file must be a name or None") if page is not None and page < 1: raise ValueError("pages are numbered from 1") super().__init__(code, file, page) self.code = code self.file = file self.page = page self.detail = detail @property def message(self) -> str: return ERRORS[self.code].message def __str__(self) -> str: return str(self.code) class ToolError(CodedError): def __init__( self, code: ErrorCode, file: str | None = None, page: int | None = None, detail: str | None = None, ) -> None: if code not in ADAPTER_CODES: raise ValueError(f"an adapter cannot raise {code}") super().__init__(code, file, page, detail) class PasswordError(CodedError): def __init__(self, files: Mapping[str, PasswordReason]) -> None: if not files or "" in files: raise ValueError("name every file that needs a password") super().__init__(ErrorCode.PASSWORD_REQUIRED) self.files = dict(files)