locustio/locust · error · LocustError

In order to use a with-block for requests, you must also pas

Error message

In order to use a with-block for requests, you must also pass catch_response=True

What it means

Locust's HttpSession request methods return a context-manager wrapper only when catch_response=True is passed. Entering a with-block without that flag means the request would not support manual success/failure marking, so __enter__ raises LocustError immediately. The library throws this to enforce that response validation is explicitly opted into.

Source

Thrown at locust/clients.py:391

    @classmethod
    def wrap_response(
        cls, response: Response, request_event: EventHook, request_meta: Mapping[str, Any], catch_response: bool
    ) -> ResponseContextManager:
        """Modify a Response object in-place, for efficiency reasons"""
        response.__class__ = ResponseContextManager
        response = cast(ResponseContextManager, response)
        response._entered = False
        response._manual_result = None
        response._request_event = request_event
        response._catch_response = catch_response
        response.request_meta = request_meta
        return response

    def __enter__(self):
        self._entered = True
        if not self._catch_response:
            raise LocustError("In order to use a with-block for requests, you must also pass catch_response=True")
        return self

    def __exit__(self, exc, value, traceback):  # type: ignore[override]
        # if the user has already manually marked this response as failure or success
        # we can ignore the default behaviour of letting the response code determine the outcome
        if self._manual_result is not None:
            if self._manual_result is True:
                self.request_meta["exception"] = None
            elif isinstance(self._manual_result, Exception):
                self.request_meta["exception"] = self._manual_result
            self._report_request()
            return exc is None

        if exc:
            if isinstance(value, ResponseError):
                self.request_meta["exception"] = value
                self._report_request()
            else:

View on GitHub (pinned to f391a716e1)

Solutions

  1. Add `catch_response=True` to the request call inside the with-block
  2. If no validation is needed, drop the with-block and call the request directly, e.g. `self.client.get(url)`
  3. Check spelling/casing of the `catch_response` kwarg

Example fix

// before
with self.client.get("/api") as response:
    if response.status_code == 200:
        response.success()
// after
with self.client.get("/api", catch_response=True) as response:
    if response.status_code == 200:
        response.success()
Defensive patterns

Strategy: validation

Validate before calling

def validate_with_block_kwargs(kwargs):
    if not kwargs.get("catch_response"):
        raise ValueError("with-block requires catch_response=True")

Type guard

null

Try / catch

try:
    with self.client.get(url, catch_response=True) as resp:
        ...
except LocustError as e:
    logger.error(" misuse of with-block: %s", e)

Prevention

When it happens

Trigger: Calling `with self.client.get(...)` / `.post(...)` etc. (any with-block on an HttpSession request) while omitting `catch_response=True` in the request kwargs.

Common situations: Developers copy the with-block syntax from docs/examples but forget the flag; refactoring a plain request into a with-block to add validation; typos like `catch_response=false` or passing it to the wrong call.

Related errors


AI-assisted analysis of locustio/locust@f391a716e1 (2026-08-29). Data as JSON: /api/errors/855f91f73d95c16e. Report an issue: GitHub.