{"id":"7149be99b640ed17","repo":"encode/httpx","slug":"the-request-property-has-not-been-set","errorCode":null,"errorMessage":"The .request property has not been set.","messagePattern":"The \\.request property has not been set\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"warning","filePath":"httpx/_exceptions.py","lineNumber":99,"sourceCode":"    For example:\n\n    ```\n    try:\n        response = httpx.get(\"https://www.example.com\")\n        response.raise_for_status()\n    except httpx.HTTPError as exc:\n        print(f\"HTTP Exception for {exc.request.url} - {exc}\")\n    ```\n    \"\"\"\n\n    def __init__(self, message: str) -> None:\n        super().__init__(message)\n        self._request: Request | None = None\n\n    @property\n    def request(self) -> Request:\n        if self._request is None:\n            raise RuntimeError(\"The .request property has not been set.\")\n        return self._request\n\n    @request.setter\n    def request(self, request: Request) -> None:\n        self._request = request\n\n\nclass RequestError(HTTPError):\n    \"\"\"\n    Base class for all exceptions that may occur when issuing a `.request()`.\n    \"\"\"\n\n    def __init__(self, message: str, *, request: Request | None = None) -> None:\n        super().__init__(message)\n        # At the point an exception is raised we won't typically have a request\n        # instance to associate it with.\n        #\n        # The 'request_context' context manager is used within the Client and","sourceCodeStart":81,"sourceCodeEnd":117,"githubUrl":"https://github.com/encode/httpx/blob/b5addb64f0161ff6bfe94c124ef76f6a1fba5254/httpx/_exceptions.py#L81-L117","documentation":"RuntimeError('The .request property has not been set.') raised by the HTTPError.request getter. Every HTTPError stores an optional _request; the getter raises if it is None. This happens when you catch an exception (typically constructed outside a request_context) and access .request before httpx has had a chance to attach one — e.g. an exception raised during client construction, an event hook, or an exception you constructed/raised manually.","triggerScenarios":"Accessing exc.request on a TimeoutException/NetworkError raised before the request was dispatched; accessing .request inside an exception handler that caught an HTTPError raised by user code (not httpx); event hooks that raise; manually raising httpx.ConnectError('msg') without passing request= and then reading .request.","commonSituations":"Logging middleware that does `print(exc.request.url)` for any caught HTTPError; retry decorators accessing exc.request; manually raising httpx exceptions in tests; transport-level errors fired before a Request object existed.","solutions":["Guard with `if exc._request is not None:` or use getattr(exc, '_request', None) before accessing.","Prefer catching the specific exception types and only accessing .request when you know a request is in flight.","When raising httpx exceptions yourself, pass request=<the request> so the property is set.","Wrap the access in try/except RuntimeError and degrade gracefully."],"exampleFix":"// before\ntry:\n    resp = client.get(url)\nexcept httpx.HTTPError as exc:\n    print(exc.request.url)  # RuntimeError if request not set\n// after\ntry:\n    resp = client.get(url)\nexcept httpx.HTTPError as exc:\n    req = getattr(exc, '_request', None)\n    print(req.url if req else '<no request>')","handlingStrategy":"type-guard","validationCode":"# Use the private _request attribute defensively\nreq = getattr(exc, '_request', None)\nurl = req.url if req is not None else '<no request>'","typeGuard":"def exception_has_request(exc: 'httpx.HTTPError') -> bool:\n    return getattr(exc, '_request', None) is not None","tryCatchPattern":"try:\n    resp = client.get(url)\nexcept httpx.HTTPError as exc:\n    req = getattr(exc, '_request', None)\n    if req is not None:\n        log.warning('request to %s failed: %s', req.url, exc)\n    else:\n        log.warning('httpx error (no request attached): %s', exc)","preventionTips":["Always read _request via getattr(exc, '_request', None), not the .request property.","When raising httpx exceptions manually, pass request=<the request>.","Distinguish exception types before assuming a request is attached.","In event hooks, do not assume exc.request is set."],"tags":["exceptions","request","api-misuse","error-handling"],"analyzedSha":"b5addb64f0161ff6bfe94c124ef76f6a1fba5254","analyzedAt":"2026-08-04T19:32:56.768Z","schemaVersion":2}