Using logger in errorhandler

Hi,

I have a new Slim4 application. In the constructor of the router I’m defining a LoggerInterface injectable like this:

$containerBuilder->addDefinitions([
  LoggerInterface::class => function (ContainerInterface $c) {
    $logger = new Logger('myApp');

I can use this throughout all my normal classes now. However, I want to use the same logger also for the error handler. The errorhandler is set in the index page like this:

$errorHandler = new HttpErrorHandler($callableResolver, $responseFactory);
$errorMiddleware->setDefaultErrorHandler($errorHandler);

My idea is that I want to override the logError function in the errorhandler to use the logger instead of error_log(). What is the best way to pass the logger Interface into this errorhandler? It seems like a basic requirement but I can not find any related documentation.

thanks!

Just add a container definition for HttpErrorHandler::class. Then you can inject the same logger.

Hi Daniel,

thanks for the reply. Could you please elaborate? When adding the HttpErrorHandler::class as container definition, how could I inject the logger there, and how would I set this errorhandler as the default errorhandler?

thanks

You can define a custom error handler like this:

$errorMiddleware->setDefaultErrorHandler(\Example\MyDefaultErrorHandler::class);

The container then resolves this class. But the handler must be a “callable”. Here is an example:

<?php

namespace Example;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Psr\Http\Message\ResponseInterface;
use Slim\Psr7\Response;
use Slim\Exception\HttpMethodNotAllowedException;
use Slim\Exception\HttpNotFoundException;
use Throwable;

class MyDefaultErrorHandler
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function __invoke(
        ServerRequestInterface $request,
        Throwable $exception,
        bool $displayErrorDetail
    ): ResponseInterface {
        $response = new Response();
        // Add error log entry
        $this->logger->error($exception->getMessage());

        // Add your custom logic here
        if ($exception instanceof HttpNotFoundException) {
            $response->getBody()->write('404 Not Found');
            $response = $response->withStatus(404);
        } elseif ($exception instanceof HttpMethodNotAllowedException) {
            $response->getBody()->write('405 Method Mot Allowed');
            $response = $response->withStatus(405);
        } else {
            $response->getBody()->write('500 Internal Server Error');
            $response = $response->withStatus(500);
        }

        return $response;
    }
}

Thanks, got it working like this!

1 Like