|
| 1 | +"""CLI error reporting helpers. |
| 2 | +
|
| 3 | +Turns ugly tracebacks into a one-line message for the user plus a |
| 4 | +self-contained log file under ~/.fli/logs/ that captures the full |
| 5 | +traceback for debugging. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import logging |
| 11 | +import sys |
| 12 | +import traceback |
| 13 | +from datetime import datetime, timezone |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +import typer |
| 17 | + |
| 18 | +from fli.cli.console import console |
| 19 | +from fli.search.exceptions import ( |
| 20 | + SearchClientError, |
| 21 | + SearchConnectionError, |
| 22 | + SearchHTTPError, |
| 23 | + SearchTimeoutError, |
| 24 | +) |
| 25 | + |
| 26 | +_LOG_DIR = Path.home() / ".fli" / "logs" |
| 27 | +_logger = logging.getLogger("fli") |
| 28 | + |
| 29 | + |
| 30 | +def _friendly_message(exc: BaseException) -> str: |
| 31 | + """Return the short, user-facing message for ``exc``.""" |
| 32 | + if isinstance(exc, SearchTimeoutError): |
| 33 | + return f"Request timed out. {exc}" |
| 34 | + if isinstance(exc, SearchConnectionError): |
| 35 | + return f"Network error. {exc}" |
| 36 | + if isinstance(exc, SearchHTTPError): |
| 37 | + return f"Google Flights error. {exc}" |
| 38 | + if isinstance(exc, SearchClientError): |
| 39 | + return f"Search failed. {exc}" |
| 40 | + return f"Unexpected error: {exc.__class__.__name__}: {exc}" |
| 41 | + |
| 42 | + |
| 43 | +def _write_log(exc: BaseException, *, command: str | None = None) -> Path: |
| 44 | + """Write the full traceback for ``exc`` to a log file and return the path.""" |
| 45 | + _LOG_DIR.mkdir(parents=True, exist_ok=True) |
| 46 | + # Microsecond precision so rapid-fire errors (e.g. tests, parallel |
| 47 | + # legs) don't collide on the same filename and silently overwrite. |
| 48 | + timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") |
| 49 | + log_path = _LOG_DIR / f"fli-error-{timestamp}.log" |
| 50 | + |
| 51 | + lines: list[str] = [] |
| 52 | + lines.append(f"timestamp: {datetime.now(timezone.utc).isoformat()}") |
| 53 | + if command: |
| 54 | + lines.append(f"command: {command}") |
| 55 | + lines.append(f"argv: {sys.argv}") |
| 56 | + lines.append(f"error_type: {exc.__class__.__module__}.{exc.__class__.__name__}") |
| 57 | + lines.append(f"error_message: {exc}") |
| 58 | + lines.append("") |
| 59 | + lines.append("traceback:") |
| 60 | + lines.append("".join(traceback.format_exception(type(exc), exc, exc.__traceback__))) |
| 61 | + |
| 62 | + log_path.write_text("\n".join(lines), encoding="utf-8") |
| 63 | + return log_path |
| 64 | + |
| 65 | + |
| 66 | +def report_cli_error( |
| 67 | + exc: BaseException, |
| 68 | + *, |
| 69 | + command: str | None = None, |
| 70 | + exit_code: int = 1, |
| 71 | +) -> typer.Exit: |
| 72 | + """Print a clean message for ``exc``, write a log file, and return a ``typer.Exit``. |
| 73 | +
|
| 74 | + Callers should ``raise`` the returned :class:`typer.Exit` so typer |
| 75 | + handles the exit code (and the original exception is suppressed from |
| 76 | + the user's terminal). |
| 77 | + """ |
| 78 | + log_path = _write_log(exc, command=command) |
| 79 | + message = _friendly_message(exc) |
| 80 | + |
| 81 | + console.print(f"[red]Error:[/red] {message}") |
| 82 | + console.print(f"[dim]Full traceback written to {log_path}[/dim]") |
| 83 | + |
| 84 | + # Still log at debug for anyone who wired up python logging. |
| 85 | + _logger.debug("CLI error", exc_info=exc) |
| 86 | + |
| 87 | + return typer.Exit(exit_code) |
| 88 | + |
| 89 | + |
| 90 | +def json_error_payload(exc: BaseException, *, command: str | None = None) -> tuple[str, str, Path]: |
| 91 | + """Return ``(message, error_type, log_path)`` for JSON-mode error output.""" |
| 92 | + log_path = _write_log(exc, command=command) |
| 93 | + if isinstance(exc, SearchTimeoutError): |
| 94 | + return str(exc), "timeout", log_path |
| 95 | + if isinstance(exc, SearchConnectionError): |
| 96 | + return str(exc), "connection_error", log_path |
| 97 | + if isinstance(exc, SearchHTTPError): |
| 98 | + return str(exc), "http_error", log_path |
| 99 | + if isinstance(exc, SearchClientError): |
| 100 | + return str(exc), "search_error", log_path |
| 101 | + return f"{exc.__class__.__name__}: {exc}", "unexpected_error", log_path |
0 commit comments