Search code examples
phpslim-3

Slim Framework 3 - Response object


In my Slim 3 application I have defined a middleware that adds a custom header to my response. The middleware is called before index routing function is called. If an exception is thrown, the error handler function is called, but it seems the $response object passed to that function is a new Response object and not the one customized in my middleware. In other words, in my response I don't have my custom header.

Is this behaviour correct?

# Middleware
$app->add(function ($request, $response, $next) {
  $response = $response->withHeader('MyCustomHeader', 'MyCustomValue');
  return $next($request, $response);
});

# Error handling
$container['errorHandler'] = function ($container) {
  return function ($request, $response, $exception) use ($container) {
    return $response->write('ERROR');
  };
};

# Index
$app->get('/index', function(Request $request, Response $response) {
  throw new exception();
  return $response->write('OK');
});

Solution

  • Yes, its correct, because:

    The Request and Response objects are immutable, therefore they need to be passed through all the functions. When throwing an exception this chain is broken and the newly created Response object (on withHeader-method) cannot get passed to the errorHandler.

    You can fix that problem by throwing a \Slim\Exception\SlimException, this exception takes 2 parameter. The request and response. With this Slim uses the request and response given in the exception inside the error handler.

    $app->get('/index', function(Request $request, Response $response) {
        throw new \Slim\Exception\SlimException($request, $response);
        return $response->write('OK');
    });