Slim4 - Route callbacks must return Response

Hey.
I’ve got TypeError from route callbacks on Slim4.
On Slim3, return value of route callbacks is either Psr\Http\Message\ResponseInterface or void(so no need to return).
On Slim4, if I don’t write return value of route callbacks as below,

$app->get("/hello", function(ServerRequestInterface $request, ResponseInterface $response, $args) {
    print("Hello world!");
});

and TypeError has occurred.

Hello world!
**Fatal error** : Uncaught TypeError: Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() must implement interface Psr\Http\Message\ResponseInterface, null returned in /Users/Shinzo/htdocs/socymslim.localhost/firstslim/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php:42 Stack trace: 
#0 /Users/Shinzo/htdocs/socymslim.localhost/firstslim/vendor/slim/slim/Slim/Routing/Route.php(370): Slim\Handlers\Strategies\RequestResponse->__invoke(Object(Closure), Object(Slim\Psr7\Request), Object(Slim\Psr7\Response), Array) 
#1 /Users/Shinzo/htdocs/socymslim.localhost/firstslim/vendor/slim/slim/Slim/MiddlewareDispatcher.php(64): Slim\Routing\Route->handle(Object(Slim\Psr7\Request)) 
#2 /Users/Shinzo/htdocs/socymslim.localhost/firstslim/vendor/slim/slim/Slim/MiddlewareDispatcher.php(64): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request)) 
#3 /Users/Shinzo/htdocs/socymslim.localhost/firstslim/vendor/slim/slim/Slim/Routing/Route.php(338): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request)) 
#4 /Users/ in  **/Users/Shinzo/htdocs/socymslim.localhost/firstslim/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php**  on line  **42**

If I write return $response;, no error.
So, Slim4’s route callbacks must return Response always. Is this right?

This is not new from Slim 4. Route callbacks must return a Response object.

1 Like

@l0gicgate Thank you for your reply! I understand.