Why can't I access the current $response inside a custom error handler?

I’m write on SF3

My problem
the middleware have authorization that can add headers to the response (access token and refresh token), but further in the route an error may occur that calls a custom error handler, and that, in turn, should change the response status to 400, put it in the response body an array of errors and display it all on the screen.

but here’s the problem - at the middleware level, there are headers, when the custom error handler is called, I look at the headers at the very beginning - there is nothing but the content type

how can I access the $ response object inside a custom error handler

class CustomHandler {
public function __invoke($request, $response, $exception) {
    $response = $response->withStatus(400);

    switch(get_class($exception)) {
        case "CustomException":
            $response = $response->withStatus(400);

        case "UnauthorizedException":
            $response = $response->withStatus(401);

        case "ForbiddenException":
            $response = $response->withStatus(403);

        case "NotFoundException":
            $response = $response->withStatus(404);
    $message = $exception->getMessage();

    return $response->withJson([
        "errors" => error_exception($message)

// dependencies.php
$container['errorHandler'] = function ($c) {
    return new CustomHandler();