@@ -137,6 +137,93 @@ return [
137137> `config/autoload/*.local.php` file with the above configuration whenever you
138138> want to enable whoops.
139139
140+ ## Listening for errors
141+
142+ When errors occur, you may want to _listen_ for them in order to provide
143+ features such as logging. `Zend\Stratigility\Middleware\ErrorHandler` provides
144+ the ability to do so via its `attachListener()` method.
145+
146+ This method accepts a callable with the following signature:
147+
148+ ```php
149+ function (
150+ Throwable|Exception $error,
151+ ServerRequestInterface $request,
152+ ResponseInterface $response
153+ ) : void
154+ ```
155+
156+ The response provided is the response returned by your error response generator,
157+ allowing the listener the ability to introspect the generated response as well.
158+
159+ As an example, you could create a logging listener as follows:
160+
161+ ``` php
162+ namespace Acme;
163+
164+ use Exception;
165+ use Psr\Log\LoggerInterface;
166+ use Psr\Http\Message\ResponseInterface;
167+ use Psr\Http\Message\ServerRequestInterface;
168+ use Throwable;
169+
170+ class LoggingErrorListener
171+ {
172+ /**
173+ * Log format for messages:
174+ *
175+ * STATUS [METHOD] path: message
176+ */
177+ const LOG_FORMAT = '%d [%s] %s: %s';
178+
179+ private $logger;
180+
181+ public function __construct(LoggerInterface $logger)
182+ {
183+ $this->logger = $logger;
184+ }
185+
186+ public function __invoke($error, ServerRequestInterface $request, ResponseInterface $response)
187+ {
188+ $this->logger->error(sprintf(
189+ self::LOG_FORMAT,
190+ $response->getStatusCode(),
191+ $request->getMethod(),
192+ (string) $request->getUri(),
193+ $error->getMessage()
194+ ));
195+ }
196+ }
197+ ```
198+
199+ You could then use a [ delegator factory] ( container/delegator-factories.md ) to
200+ create your logger listener and attach it to your error handler:
201+
202+ ``` php
203+ namespace Acme;
204+
205+ use Psr\Container\ContainerInterface;
206+ use Psr\Log\LoggerInterface;
207+ use Zend\Stratigility\Middleware\ErrorHandler;
208+
209+ class LoggerErrorListenerDelegatorFactory
210+ {
211+ /**
212+ * @param ContainerInterface $container
213+ * @param string $name
214+ * @param callable $callback
215+ * @return ErrorHandler
216+ */
217+ public function __invoke(ContainerInterface $container, $name, callable $callback)
218+ {
219+ $listener = new LoggerErrorListener($container->get(LoggerInterface::class));
220+ $errorHandler = $callback();
221+ $errorHandler->attachListener($listener);
222+ return $errorHandler;
223+ }
224+ }
225+ ```
226+
140227## Handling more specific error types
141228
142229You could also write more specific error handlers. As an example, you might want
0 commit comments