Database as JSON

Hello all, im new at Slim4 and i need some help. I wrote a script with Slim4 and a Database-Connection. Now i want to get the datas as json. But i didnt get it. Can someone help me? My script looks like:

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
$app = AppFactory::create();
    //Fächer auslesen
    $app->get('/ReadAPI/faecher', function (Request $request, Response $response) {
    
    $sql = "SELECT * FROM faecher";
    
    try 
    {
        //Get DB Object
        $db = new db();
        //Verbindung herstellen
        $db = $db->connect();
        
        $stmt = $db->query($sql);   
        $faecher = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
  
        $response->getBody()->write(json_encode($faecher));       
        return($response)
            ->withHeader('content-type', 'application/json')
            ->withStatus(200);
        
        
    } 
    catch (PDOException $e) 
    {
        echo '{"error": {"text": '.$e->getMessage().'}';
    }
	
});

And i get an error:

Fatal error: Uncaught TypeError: fwrite() expects parameter 2 to be string, bool given in

Thank you for your help!
Greetings
Sascha

The json_encode function returns false on failure.

Change the result set to array first:

$faecher = $stmt->fetchAll(PDO::FETCH_ASSOC);

Then try adding the JSON_THROW_ON_ERROR as the second parameter to see what is wrong with the database result set.

$response->getBody()->write(json_encode($faecher, JSON_THROW_ON_ERROR)):

Then change the return statement to this:

return $response
    ->withHeader('Content-Type', 'application/json')
    ->withStatus(200);

Optional: Change the catch block to prevent JSON syntax errors:

    catch (\Exception $e) 
    {
        $response->getBody()->write(
            json_encode(
                [
                    'error' => [
                        'message' => $e->getMessage(),
                    ]
                ]
            ),
            JSON_THROW_ON_ERROR
        );

        return $response
            ->withHeader('Content-Type', 'application/json')
            ->withStatus(500);
    }

Thank you for your help!

Now i get this error:

{"error":{"message":null}}

There was a typo. It should be 'message' => $e->getMessage(),