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
TIF1Errorcarries acontextdictionary 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
Exception Hierarchy
The exception hierarchy allows errors to be caught at different levels of specificity. Catch broad categories (likeTIF1Error 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:
message(str): Human-readable error message describing what went wrongcontext(dict[str, Any]): Dictionary containing structured contextual information about the error
- All context keyword arguments are automatically stored in the
contextdictionary - The message is both stored as an attribute and passed to the base
Exceptionclass - Subclasses can add their own context keys while preserving the base functionality
- Never raised directly; always use a more specific subclass
- Used as a catch-all to handle any tif1 error
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.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:
message attribute and no context dictionary. Use str(e) to get the message.
When Raised:
get_session()andget_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 isNo event matching '<name>' in <year>. This case raises the subclassFuzzyMatchError.get_event_by_name(..., exact_match=True)finds no event with that exact name. It raises the subclassExactEventNotFoundError, which is also aKeyError(fastf1 raisesKeyError). The message isNo exact match found for event '<name>' in <year>.
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:
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
**contextkwargs
- 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:
tif1remembers the verdict formissing_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:
- Future Sessions: Requesting data for races that have not happened yet
- Historical Gaps: Some older seasons have incomplete data coverage
- Missing Files: One data file (for example, weather) is absent for a session that has lap data
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:
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)
- 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
- Typos: “HAM” vs “HAN”, “VER” vs “VET”
- Wrong Session: Driver participated in practice but not qualifying
- Historical Changes: Driver codes changed between seasons
- 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:
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:
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")
- 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
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:
- Out of Range: Requesting lap 60 when the driver only completed 45 laps
- Early Retirement: Driver crashed on lap 10, requesting lap 20
- Float Lap Numbers:
LapNumberis a float column; passint(lap["LapNumber"]), becauseget_lap(10.0)raisesTypeError
fastf1 Names
tif1 exports the fastf1 exception names, so fastf1except 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:
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 URLstatus_code(int | None): HTTP status code of the last failed source (for example, 500, 502, 503, 504).Nonewhen the request failed before a response (timeout, DNS failure)- Additional context from
**contextkwargs
- 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
- CDN Outage: One or more CDN sources (jsDelivr, Hugging Face buckets, StaticDelivr) experiencing downtime or degraded performance
- Local Network: No internet connection or restrictive firewall
- Server Errors: Backend infrastructure experiencing issues
- Timeout: Requests taking too long due to slow network or large files
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.
- 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.)
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:
timeout configuration key (seconds, default 30):
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:
reason(str | None): Detailed description of why the data is invalid- Additional context from
**contextkwargs (may include field names, expected vs actual values, etc.)
- 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 withstrict=Trueon 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)
- Malformed JSON: CDN served corrupted or incomplete JSON
- Schema Changes: Data structure changed but library not updated
- Strict Validation: A
validate_lap_data(..., strict=True)call gets a payload that fails a check
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: ....tif1then 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 logsCannot clear cache (no connection or read-only mode)and returns.
CacheError stays available for application code that wants to report its own cache problems in the TIF1Error tree.
Signature:
- Any keyword arguments passed by the code that raises it
tif1.cache logger. Show them while debugging:
invalidate() limits the scope: "memory", "json", "telemetry", or "all":
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:
attribute(str | None): The attribute that the raising code names
Session data not loaded. Access '<attribute>' requires loading data first., or Session data not loaded without an attribute.
Example - Access Loads the Data:
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:
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:
operation(str | None): The synchronous operation, for examplelaps propertyalternative(str | None): The coroutine to await instead, for examplesession.laps_async()
`<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
EveryTIF1Error 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
Thecontext 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
contextdictionary - ✓ 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