errorHandler dont work with exceptions in container values

Hello. Look at my code and say me, where i have bad way…

$app = new \Slim\App(['settings'=>['displayErrorDetails' => true]]);
$container = $app->getContainer();
$container['errorHandler'] = function ($c) {
  return function ($request, $response, $exception) use ($c) {
    return $response->withStatus(500)->withJson([
     'result' => false, 'message' => $exception->getMessage()
   ]);
  };
};
$container['testException'] = function ($c)  {
  throw ner Exception('test');

 return [];
}
$app->run();
$app->get('/',function (Request $request, Response $response, array $args) use ($app) {

$exception = $app->getContainer()['testException'];
//Here erroHandler must return me json, but no:( i take 500 status code and exception in my apache2 log.
}

Help me pls solve this problem; Thx for ur time.
p.s. sorry for my bad english.

Resolve this issue by return zero value when cath exception and handle this in middleware:

class RequestTypeService
 {
  const API_TYPE = 'API';
  const BROWSER_TYPE = 'BROWSER';

  public function getType(Request $request): string
  {
    $acceptHeader = $request->getHeaderLine('HTTP_ACCEPT');
    
    return strpos($acceptHeader, 'text/html') !== false ? self::BROWSER_TYPE : self::API_TYPE;
  }
}
class CheckDBMiddleware
{
  private $container;
  public function __construct(ContainerInterface $container)
  {
$this->container = $container;
  }

  public function __invoke(Request $request, Response $response, callable $next)
  {
if (!$this->container['db'] instanceof \PDO) {      
  if ($this->container[RequestTypeService::class]->getType($request) == RequestTypeService::API_TYPE) {
    $response = $response->withJson(['result' => FALSE, 'message' => 'Bad database connection'], 500);
  } else {
    $response = new \Slim\Http\Response(500);
    return $this->container['renderer']->render($response ,'PDOException.phtml',[]);
  }
} else {
  $response = $next($request, $response);
}

return $response;
  }
}
$app->add(\App\Middleware\CheckDBMiddleware::class);
$app->run();