Skip to main content

Overview

tif1 implements a structured exception hierarchy designed for clarity and debuggability when errors occur. The data, network, and cache exceptions inherit from the base TIF1Error class. Each of them includes contextual information that shows what went wrong and why. Name errors are different: an unknown session name or round number raises a plain ValueError. An event name that matches no event raises EventNotFoundError, a ValueError subclass. The exception system is designed with several key principles:
  • Structured Context: Every TIF1Error carries a context dictionary with relevant metadata (year, event, driver, URL, etc.)
  • Clear Hierarchy: Exceptions are organized in a logical tree structure. Catch errors at the appropriate level of specificity
  • Actionable Messages: Error messages are automatically constructed with relevant details to aid debugging
  • Type Safety: All exceptions are properly typed for IDE autocomplete and type checking
  • Graceful Degradation: The design encourages handling errors gracefully rather than crashing
This guide covers every exception type in detail. It explains when each exception is raised, what context it provides, and how to handle it.

Exception Hierarchy

The exception hierarchy allows errors to be caught at different levels of specificity. Catch broad categories (like TIF1Error for any library error) or specific exceptions (like DriverNotFoundError for missing drivers).
DriverNotFoundError has two bases: DataNotFoundError and ValueError. fastf1 raises ValueError for an unknown get_driver() identifier, so a fastf1 except ValueError handler still catches it. Put an except DriverNotFoundError clause before an except ValueError clause. EventNotFoundError and its subclasses are not TIF1Error subclasses. Refer to Event Name Errors for details. The fastf1 exception names are covered in fastf1 Names.
get_session() does not fetch data. A DataNotFoundError or NetworkError appears on the first data access: session.load(), session.laps, session.drivers, and similar properties. Data properties load on first access, so SessionNotLoadedError does not occur. A cache failure is logged as a warning, and tif1 continues without the SQLite cache, so CacheError does not occur either.

Catching Strategy

The hierarchy allows flexible error handling:

Base Exception

TIF1Error

The root exception class for tif1 errors. Every tif1 exception class except EventNotFoundError and its subclasses (FuzzyMatchError, EventNotInSeasonError, ExactEventNotFoundError, all ValueErrors) inherits from this class. A single except clause on TIF1Error catches all of them. Signature:
Attributes:
  • message (str): Human-readable error message describing what went wrong
  • context (dict[str, Any]): Dictionary containing structured contextual information about the error
Key Features:
  • All context keyword arguments are automatically stored in the context dictionary
  • The message is both stored as an attribute and passed to the base Exception class
  • Subclasses can add their own context keys while preserving the base functionality
When Raised:
  • Never raised directly; always use a more specific subclass
  • Used as a catch-all to handle any tif1 error
Example - Basic Usage:
An unknown event name does not raise TIF1Error. A name that matches no event raises EventNotFoundError, a ValueError. A typo such as “Monacco” resolves to the closest event and logs a warning. Check session.event_name when the name comes from user input.
Example - Logging with Context:
Example - Custom Error Handling:

Event Name Errors

EventNotFoundError

Raised when an event name matches no event of the season. It is a ValueError subclass, not a TIF1Error. Import it as tif1.EventNotFoundError or from tif1.exceptions. Signature:
The exception has no message attribute and no context dictionary. Use str(e) to get the message. When Raised:
  • get_session() and get_event_by_name() get a name that resembles no event. Event resolution tries the exact name (case-insensitive), then the alias table, then fuzzy matching. A fuzzy match needs a score of at least 70 (rapidfuzz ratio, 0-100). The message is No event matching '<name>' in <year>. This case raises the subclass FuzzyMatchError.
  • get_event_by_name(..., exact_match=True) finds no event with that exact name. It raises the subclass ExactEventNotFoundError, which is also a KeyError (fastf1 raises KeyError). The message is No exact match found for event '<name>' in <year>.
A season with no events raises a plain ValueError (No events found for <year>). A typo such as “Monacco” or “Zandvort” still resolves to the closest event and logs a Correcting user input warning. Example:

EventNotInSeasonError

Raised when an alias names a Grand Prix that is not on the calendar of that season. It is a subclass of FuzzyMatchError and so of EventNotFoundError: an except clause on either class also catches it. Import it as tif1.EventNotInSeasonError. get_session() and get_event_by_name() raise it, for example for tif1.get_session(2021, "Suzuka", "Race"). The message names the event: 'Suzuka' refers to the Japanese Grand Prix, which is not on the 2021 calendar.

FuzzyMatchError

The fastf1 name for a failed fuzzy event match. It is a subclass of EventNotFoundError and a ValueError. Import it as tif1.FuzzyMatchError. get_session(), get_event_by_name(), and get_sessions() raise it for a name below the fuzzy score floor (No event matching '<name>' in <year>). An except FuzzyMatchError clause from fastf1 code and an except EventNotFoundError clause both catch it. A miss with exact_match=True raises ExactEventNotFoundError instead, an EventNotFoundError and a KeyError.

Data Errors

DataNotFoundError

Raised when requested F1 data is not available in the CDN or cache. This is one of the most common exceptions. It typically occurs for a session on the calendar that has not run yet. It also occurs when a data file was never published. Signature:
Context Keys:
  • year (int | None): The requested year (for example, 2024)
  • event (str | None): The requested event/Grand Prix name (for example, “Monaco Grand Prix”)
  • session (str | None): The requested session type (for example, “Race”, “Qualifying”, “FP1”)
  • Additional context from **context kwargs
When Raised:
  • Every CDN source refuses the file with an HTTP 4xx status other than 408 or 429, such as 404 (no such file)
  • Requesting a session that is on the calendar but has not run yet
  • Requesting a data file that was never published for a session
  • A file that every CDN refused recently: tif1 remembers the verdict for missing_payloads_ttl_days (default 7) and raises without a new request
DataNotFoundError comes from the first data access, not from get_session(). A session name that the event does not have, such as “Sprint” on a conventional weekend, raises ValueError from get_session() instead. Common Scenarios:
  1. Future Sessions: Requesting data for races that have not happened yet
  2. Historical Gaps: Some older seasons have incomplete data coverage
  3. Missing Files: One data file (for example, weather) is absent for a session that has lap data
Example - Basic Handling:
Example - Checking Data Availability:
Example - Fallback to Alternative Session:
Example - Batch Processing with Error Tracking:

DriverNotFoundError

Raised when attempting to access a driver that does not exist in the session. This is a subclass of DataNotFoundError and of ValueError, the exception that fastf1 raises for an unknown driver. It typically occurs due to typos in driver codes. It also occurs when requesting drivers who did not participate in the session. Signature:
Context Keys:
  • driver (str): The requested driver code (for example, “VER”, “HAM”)
  • year (int | None): Session year (if provided in context)
  • event (str | None): Event name (if provided in context)
  • session (str | None): Session name (if provided in context)
When Raised:
  • Calling session.get_driver("XXX") with an invalid driver code or car number
  • Driver code typos (for example, “VET” instead of “VER”)
  • Requesting a driver who did not participate in that specific session
  • Driver retired/withdrew before the session
Common Causes:
  1. Typos: “HAM” vs “HAN”, “VER” vs “VET”
  2. Wrong Session: Driver participated in practice but not qualifying
  3. Historical Changes: Driver codes changed between seasons
  4. Case Sensitivity: Driver codes are case-sensitive ("ver" raises; use "VER")
get_driver() also accepts the car number ("1" or 1). session.drivers holds car numbers in classification order, and session.drivers_df["Driver"] holds the three-letter codes. Example - Basic Handling:
Example - Fuzzy Driver Matching:
Example - Safe Driver Access:
Example - Validating Driver List:
Example - Batch Driver Analysis:

LapNotFoundError

Raised when attempting to access a specific lap number that does not exist for a driver. This is a subclass of DataNotFoundError. It typically occurs when requesting lap numbers beyond what the driver completed. Signature:
Context Keys:
  • lap_number (int | None): The requested lap number (for example, 1, 50, 999)
  • driver (str | None): The driver code for whom the lap was requested (for example, “VER”, “HAM”)
  • year, event, session: The session of the request, with plain names ("Monaco Grand Prix", "Race")
When Raised:
  • Calling driver.get_lap(N) where N exceeds the driver’s total lap count
  • Requesting laps from drivers who retired early in the session
  • Requesting a lap number that the driver does not have in the data
A lap number below 1 raises ValueError (lap_number must be positive), and a non-integer raises TypeError. Deleted laps (track limits) stay in the data with Deleted set to True, so get_lap() returns them. Common Scenarios:
  1. Out of Range: Requesting lap 60 when the driver only completed 45 laps
  2. Early Retirement: Driver crashed on lap 10, requesting lap 20
  3. Float Lap Numbers: LapNumber is a float column; pass int(lap["LapNumber"]), because get_lap(10.0) raises TypeError
Example - Basic Handling:
Example - Safe Lap Access:
Example - Validating Lap Range:
Example - Finding Last Valid Lap:
Example - Analyzing Lap Completion:
Example - Laps Completed per Driver:

fastf1 Names

tif1 exports the fastf1 exception names, so fastf1 except clauses import without change. Import them from tif1 or from tif1.exceptions.

FastF1CriticalError

The base class of errors that tif1.logger.soft_exceptions always raises again. A function wrapped in soft_exceptions logs and swallows every other exception. RateLimitExceededError is a FastF1CriticalError and also a NetworkError.

Network Errors

NetworkError

Raised when HTTP network requests fail after all retries and CDN fallback mechanisms are exhausted. This exception indicates a network connectivity issue, server unavailability, or infrastructure problem. Such problems prevent data retrieval. The library implements retry logic with exponential backoff and circuit breaker patterns before raising this exception. A NetworkError means that no CDN source delivered the file. A 4xx refusal from every source raises DataNotFoundError instead. Signature:
Context Keys:
  • url (str | None): The CDN path that failed, without the CDN host (for example, "2024/Monaco%20Grand%20Prix/Race/drivers.json"). Absolute-URL fetches (schedule files) report the full URL
  • status_code (int | None): HTTP status code of the last failed source (for example, 500, 502, 503, 504). None when the request failed before a response (timeout, DNS failure)
  • Additional context from **context kwargs
When Raised:
  • All CDN sources (jsDelivr, Hugging Face buckets, StaticDelivr) fail with a server error or a transport error
  • HTTP 5xx server errors (500, 502, 503, 504) persisting after retries (max_retries, default 3)
  • Connection timeouts exceeding the configured timeout (default 30 seconds)
  • DNS resolution failures and SSL/TLS errors
  • Network connectivity issues (no internet connection)
  • Firewall or proxy blocking requests
Common Scenarios:
  1. CDN Outage: One or more CDN sources (jsDelivr, Hugging Face buckets, StaticDelivr) experiencing downtime or degraded performance
  2. Local Network: No internet connection or restrictive firewall
  3. Server Errors: Backend infrastructure experiencing issues
  4. Timeout: Requests taking too long due to slow network or large files
Subclass CircuitBreakerOpenError: The shared circuit breaker (tif1.retry.CircuitBreaker) opens after circuit_breaker_threshold failures (default 5). While it is open, CircuitBreaker.call() refuses calls with CircuitBreakerOpenError for circuit_breaker_timeout seconds (default 60). The message is Circuit breaker is open. It is a NetworkError, so except tif1.NetworkError also catches it. The class is exported as tif1.CircuitBreakerOpenError and tif1.exceptions.CircuitBreakerOpenError.
HTTP Status Codes:
  • 500 Internal Server Error: CDN or origin server error
  • 502 Bad Gateway: CDN cannot reach origin server
  • 503 Service Unavailable: Server temporarily overloaded or down
  • 504 Gateway Timeout: CDN timeout waiting for origin server
  • None: Connection failed before receiving response (timeout, DNS failure, etc.)
Example - Basic Handling:
Example - Retry with Exponential Backoff:
Example - Offline Mode with Cached Data: tif1 reads the SQLite cache before it contacts a CDN, so a NetworkError means that the file is not in the cache. With offline_mode, tif1 uses only cached data and makes no network requests. A lap file that is not in the cache does not raise in this mode. tif1 logs Failed to fetch ... for each missing file and returns fewer laps, or none:
Example - Network Health Check:
Example - Timeout Configuration: The request timeout is the timeout configuration key (seconds, default 30):
Example - Batch Loading with Error Tracking:
Example - Monitoring and Alerting:

Data Validation Errors

InvalidDataError

Raised when fetched data is invalid, corrupted, malformed, or fails validation checks. This exception indicates that the network request succeeded and data was retrieved. The data itself does not meet the format, schema, or quality standards required by the library. This is distinct from DataNotFoundError (data does not exist) and NetworkError (could not retrieve data). InvalidDataError means the data was retrieved but is unusable. Signature:
Context Keys:
  • reason (str | None): Detailed description of why the data is invalid
  • Additional context from **context kwargs (may include field names, expected vs actual values, etc.)
When Raised:
  • JSON parsing failures (malformed JSON syntax)
  • A payload of the wrong type (for example, a list where a JSON object is expected)
  • A validate_*_data() call with strict=True on a payload that fails a check. The fetch pipeline runs these validators in non-strict mode: a payload that fails a check is logged and passed through
  • Malformed schedule data (see the Schedule Schema API)
Common Scenarios:
  1. Malformed JSON: CDN served corrupted or incomplete JSON
  2. Schema Changes: Data structure changed but library not updated
  3. Strict Validation: A validate_lap_data(..., strict=True) call gets a payload that fails a check
Example - Basic Handling:
Example - Detailed Error Inspection:
Example - Graceful Degradation:
Example - Data Quality Checks:
Example - Batch Validation:
Example - Custom Validation Rules:
Example - Error Reporting:

Cache Errors

CacheError

A TIF1Error subclass for cache operation failures. tif1 defines and exports it, but the current library does not raise it. The SQLite cache handles its own failures:
  • A cache that cannot open (permission denied, read-only filesystem, corrupt file) logs the warning SQLite cache unavailable: .... tif1 then runs without the SQLite tier and fetches data from the CDN.
  • A failed cache read logs Cache read error for ... and counts as a cache miss.
  • cache.clear() on a cache without a connection logs Cannot clear cache (no connection or read-only mode) and returns.
So cache problems show up as log warnings and slower loads, not as exceptions. CacheError stays available for application code that wants to report its own cache problems in the TIF1Error tree. Signature:
Context Keys:
  • Any keyword arguments passed by the code that raises it
Example - Raising CacheError in Application Code:
Example - Show Cache Warnings: Cache failures are logged by the tif1.cache logger. Show them while debugging:
Example - Cache Diagnostics:
Example - Cache Repair: When the cache data looks wrong, clear it. invalidate() limits the scope: "memory", "json", "telemetry", or "all":
Example - Cache Monitoring:
Example - Cache Configuration: Set the cache directory with the cache_dir configuration key (or the TIF1_CACHE_DIR environment variable) before the first data access. Turn the cache off with enable_cache:

Session State Errors

SessionNotLoadedError

A TIF1Error subclass for access to session data before a load. DataNotLoadedError (the fastf1 name) is the same class object. tif1 defines and exports it, but the current library does not raise it. Data properties load on first access: session.laps, session.weather, session.race_control_messages, session.drivers, and session.results fetch their data when the code reads them. session.load() only controls which data is fetched in one call. Signature:
Context Keys:
  • attribute (str | None): The attribute that the raising code names
The message is Session data not loaded. Access '<attribute>' requires loading data first., or Session data not loaded without an attribute. Example - Access Loads the Data:
Example - Explicit Loading Pattern: session.load() fetches several data types in one call. Its default is laps=True, telemetry=True, weather=True, messages=True, and telemetry=True fetches the telemetry of every lap. Turn off what is not needed:
Example - Selective Loading:
Example - Progressive Loading:

Runtime Errors

AsyncRequiredError

A TIF1Error subclass raised when a synchronous entry point cannot wait on its network fetch. Inside Pyodide the event loop belongs to the browser. Synchronous code can only wait on it through JavaScript Promise Integration (JSPI). Without JSPI (Firefox and Safari by default, or code entered through runPython instead of runPythonAsync), session.load(), session.laps, and the other blocking entry points raise this error. The async counterpart named in the message works in each browser. Refer to Pyodide and the Browser. Signature:
Context Keys:
  • operation (str | None): The synchronous operation, for example laps property
  • alternative (str | None): The coroutine to await instead, for example session.laps_async()
The message is `<operation>` cannot block on network fetches in this runtime (no JavaScript Promise Integration); use `await <alternative>` instead. Example - Fall Back to the Async API:

Ergast Errors

ErgastError

The base class of the errors raised by tif1.ergast (fastf1 keeps the same three names in fastf1.exceptions). A TIF1Error subclass.

ErgastJsonError

Raised when a Jolpica answer is not a JSON object with the MRData envelope.

ErgastInvalidRequestError

Raised when the Jolpica API rejects a request (a 404 for an unknown path or any other non-200 answer). Also raised when a query needs Jolpica while ergast_fallback is off. The message carries the request URL and the server’s answer; the context holds url and status_code.

RateLimitExceededError

A NetworkError subclass raised when Jolpica keeps answering 429 Too Many Requests after three retries that honour Retry-After. It is also a FastF1CriticalError, so tif1.logger.soft_exceptions never swallows it. The context holds url, status_code (429) and retry_after. Example:

Error Handling Patterns

This section provides patterns for handling tif1 exceptions in real-world applications. These patterns demonstrate best practices for reliability, maintainability, and user experience.

Basic Try-Catch Pattern

The fundamental pattern for handling tif1 exceptions. Always catch specific exceptions before general ones to enable targeted error handling.

Specific Error Handling Pattern

Handle specific errors with targeted recovery strategies.

Retry with Exponential Backoff Pattern

Implement retry logic for transient network errors.

Circuit Breaker Pattern

Implement circuit breaker to prevent cascading failures.

Fallback Chain Pattern

Implement multiple fallback strategies in sequence.

Context-Aware Error Handling Pattern

Extract and use structured context for error handling.

Best Practices

Guidelines for reliable error handling in production applications using tif1.

1. Catch Specific Exceptions First

Always catch more specific exceptions before general ones. Python evaluates except clauses in order, so place specific handlers first. Why: Specific exceptions allow targeted recovery strategies and better error messages.

2. Always Use Context Information

Every TIF1Error includes a context dictionary with structured metadata. Use this for debugging, logging, and error recovery. Why: Context provides actionable information for debugging and monitoring.

3. Never Swallow Errors Silently

Always log errors or provide user feedback. Silent failures make debugging impossible. Why: Silent failures hide problems and make debugging difficult.

4. Implement Retries for Network Errors

Network errors are often transient. Implement retry logic with exponential backoff. Why: Temporary network issues should not cause permanent failures.

5. Validate User Input Early

Check user input before making expensive API calls or network requests. Why: Fail fast with clear error messages rather than cryptic exceptions later.

6. Use Try-Finally for Resource Cleanup

Ensure resources are cleaned up even when errors occur. Why: Prevents resource leaks and ensures consistent state.

7. Log Context for Debugging

The context dictionary contains valuable debugging information. Always log it. Why: Structured context enables effective debugging and monitoring.

8. Provide User-Friendly Error Messages

Translate technical errors into actionable user messages. Why: Users need clear guidance, not technical jargon.

9. Implement Graceful Degradation

When possible, provide partial functionality rather than complete failure. Why: Better user experience and more resilient applications.

10. Use Type Hints and Documentation

Document exception behavior in docstrings and use type hints. Why: Clear documentation prevents misuse and aids maintenance.

11. Monitor and Alert on Errors

Implement monitoring for production applications. Why: Proactive error detection prevents user impact.

12. Test Error Handling

Write tests for error scenarios. Why: Ensures error handling works correctly.

Summary Checklist

When handling tif1 exceptions:
  • ✓ Catch specific exceptions before general ones
  • ✓ Use and log the context dictionary
  • ✓ Never swallow errors silently
  • ✓ Implement retries for network errors
  • ✓ Validate user input early
  • ✓ Use try-finally for cleanup
  • ✓ Log structured context for debugging
  • ✓ Provide user-friendly error messages
  • ✓ Implement graceful degradation where possible
  • ✓ Document exception behavior
  • ✓ Monitor errors in production
  • ✓ Test error handling code
Last modified on October 30, 2026