From 2ce12b3fc57acdd97ab092c79788778056aa825f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 09:54:38 +0000 Subject: [PATCH] feat(exception): v13 report/render API in the exception Handler (task 4.5) The Handler reports and renders the way v13's Foundation Handler does, so an app's error handling written against it keeps its meaning after the flip: - reportable() (a ReportableHandler: typed by its first parameter, false or stop() ends reporting), dontReport(), stopIgnoring() and v13's internal don't-report list. report() runs the exception's own report(), then the callbacks, then logs the message with the exception (and userId) as context. - renderable() callbacks run in registration order, first response wins, after the exception's own render()/Responsable and prepareException() (ModelNotFound -> 404, TokenMismatch -> 419, ...). An HttpResponseException answers with its response; anything else falls back to the displayers, as before. - handleException() reports, then renders the current request; the worker adapter reports and renders through the same methods. - Foundation\Configuration\Exceptions, v13's withExceptions() object, with render/report/dontReport/stopIgnoring. - App::error(), pushError(), missing() and fatal() go, with the newest-first handler list behind them: v13 has none of them. Tinker's silencing handler becomes a render callback. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0169SsatCE8LhaTsQTPiGtVo --- .../Exception/ExceptionHandlerAdapter.php | 6 +- src/Illuminate/Exception/Handler.php | 392 +++++++++++------- src/Illuminate/Foundation/Application.php | 51 --- .../Foundation/Configuration/Exceptions.php | 76 ++++ .../Foundation/Console/TinkerCommand.php | 2 +- .../Exceptions/ReportableHandler.php | 81 ++++ tests/Exception/HandlerTest.php | 286 +++++++++---- tests/Queue/QueueForkBridgeTest.php | 2 +- 8 files changed, 609 insertions(+), 287 deletions(-) create mode 100644 src/Illuminate/Foundation/Configuration/Exceptions.php create mode 100644 src/Illuminate/Foundation/Exceptions/ReportableHandler.php diff --git a/src/Illuminate/Exception/ExceptionHandlerAdapter.php b/src/Illuminate/Exception/ExceptionHandlerAdapter.php index dcfb7e5d..2ba26b79 100644 --- a/src/Illuminate/Exception/ExceptionHandlerAdapter.php +++ b/src/Illuminate/Exception/ExceptionHandlerAdapter.php @@ -40,7 +40,7 @@ public function __construct(Handler $handler) */ public function report(Throwable $e) { - $this->handler->handleConsole($e); + $this->handler->report($e); } /** @@ -51,7 +51,7 @@ public function report(Throwable $e) */ public function shouldReport(Throwable $e) { - return true; + return $this->handler->shouldReport($e); } /** @@ -63,7 +63,7 @@ public function shouldReport(Throwable $e) */ public function render($request, Throwable $e) { - return $this->handler->handleException($e); + return $this->handler->render($request, $e); } /** diff --git a/src/Illuminate/Exception/Handler.php b/src/Illuminate/Exception/Handler.php index 9c1370b6..5729c97a 100755 --- a/src/Illuminate/Exception/Handler.php +++ b/src/Illuminate/Exception/Handler.php @@ -2,19 +2,51 @@ use Closure; use ErrorException; -use ReflectionFunction; +use Throwable; +use Illuminate\Auth\Access\AuthorizationException; +use Illuminate\Auth\AuthenticationException; +use Illuminate\Container\Container; +use Illuminate\Contracts\Support\Responsable; +use Illuminate\Database\Eloquent\ModelNotFoundException; +use Illuminate\Database\RecordNotFoundException; +use Illuminate\Database\RecordsNotFoundException; +use Illuminate\Foundation\Exceptions\ReportableHandler; +use Illuminate\Http\Exceptions\HttpResponseException; +use Illuminate\Http\Exceptions\OriginMismatchException; +use Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException; +use Illuminate\Routing\Router; +use Illuminate\Session\TokenMismatchException; +use Illuminate\Support\Arr; use Illuminate\Support\Contracts\ResponsePreparerInterface; +use Illuminate\Support\Reflector; +use Illuminate\Support\Traits\ReflectsClosures; +use Illuminate\Validation\ValidationException; use Symfony\Component\ErrorHandler\Error\FatalError; -use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; - +use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; +use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; +use Symfony\Component\HttpKernel\Exception\HttpException; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; + +/** + * Reports and renders exceptions the way v13's Foundation\Exceptions\Handler does + * (task 4.5): report callbacks, dontReport/stopIgnoring and the internal + * don't-report list, then render callbacks in registration order after + * prepareException(). Apps register through Foundation\Configuration\Exceptions, + * the object v13's withExceptions() hands them. When no callback answers, the + * fork's displayers render the exception, as before. + */ class Handler { + use ReflectsClosures; + /** - * The response preparer implementation. + * The application instance. * - * @var \Illuminate\Support\Contracts\ResponsePreparerInterface + * @var \Illuminate\Container\Container&\Illuminate\Support\Contracts\ResponsePreparerInterface */ - protected $responsePreparer; + protected $app; /** * The plain exception displayer. @@ -38,37 +70,64 @@ class Handler { protected $debug; /** - * All of the register exception handlers. + * The callbacks that should be used during reporting. + * + * @var \Illuminate\Foundation\Exceptions\ReportableHandler[] + */ + protected $reportCallbacks = array(); + + /** + * The callbacks that should be used during rendering. * - * @var array + * @var \Closure[] */ - protected $handlers = array(); + protected $renderCallbacks = array(); /** - * All of the handled error messages. + * A list of the exception types that are not reported. * - * @var array + * @var array> */ - protected $handled = array(); + protected $dontReport = array(); + + /** + * A list of the internal exception types that should not be reported. + * + * @var array> + */ + protected $internalDontReport = array( + AuthenticationException::class, + AuthorizationException::class, + BackedEnumCaseNotFoundException::class, + HttpException::class, + HttpResponseException::class, + ModelNotFoundException::class, + OriginMismatchException::class, + RecordNotFoundException::class, + RecordsNotFoundException::class, + RequestExceptionInterface::class, + TokenMismatchException::class, + ValidationException::class, + ); /** * Create a new error handler instance. * - * @param \Illuminate\Support\Contracts\ResponsePreparerInterface $responsePreparer + * @param \Illuminate\Container\Container&\Illuminate\Support\Contracts\ResponsePreparerInterface $app * @param \Illuminate\Exception\ExceptionDisplayerInterface $plainDisplayer * @param \Illuminate\Exception\ExceptionDisplayerInterface $debugDisplayer * @param bool $debug * @return void */ - public function __construct(ResponsePreparerInterface $responsePreparer, + public function __construct(Container&ResponsePreparerInterface $app, ExceptionDisplayerInterface $plainDisplayer, ExceptionDisplayerInterface $debugDisplayer, $debug = false) { + $this->app = $app; $this->debug = $debug; $this->plainDisplayer = $plainDisplayer; $this->debugDisplayer = $debugDisplayer; - $this->responsePreparer = $responsePreparer; } /** @@ -136,36 +195,26 @@ public function handleError($level, $message, $file = '', $line = 0, $context = } /** - * Handle an exception for the application. + * Report the given exception and render it for the current request. * - * @param \Exception $exception + * @param \Throwable $exception * @return \Symfony\Component\HttpFoundation\Response */ public function handleException($exception) { try { - $response = $this->callCustomHandlers($exception); + $this->report($exception); - // If one of the custom error handlers returned a response, we will send that - // response back to the client after preparing it. This allows a specific - // type of exceptions to handled by a Closure giving great flexibility. - if ( ! is_null($response)) { - return $this->prepareResponse($response); - } - } catch (\Throwable $throwable) { - $exception = $throwable; - } - - // If no response was sent by this custom exception handler, we will call the - // default exception displayer for the current application context and let - // it show the exception to the user / developer based on the situation. - return $this->displayException($exception); + return $this->render($this->app['request'], $exception); + } catch (Throwable $throwable) { + return $this->displayException($throwable); + } } /** * Handle an uncaught exception. * - * @param \Exception $exception + * @param \Throwable $exception * @return void */ public function handleUncaughtException($exception) @@ -205,174 +254,239 @@ protected function isFatal($type) } /** - * Handle a console exception. + * Register a reportable callback. * - * @param \Exception $exception - * @return void + * @param callable $reportUsing + * @return \Illuminate\Foundation\Exceptions\ReportableHandler */ - public function handleConsole($exception) + public function reportable(callable $reportUsing) { - try { - return $this->callCustomHandlers($exception, true); - } catch (\Throwable $throwable) { - return $throwable->getMessage(); - } + if ( ! $reportUsing instanceof Closure) + { + $reportUsing = Closure::fromCallable($reportUsing); + } + + return $this->reportCallbacks[] = new ReportableHandler($reportUsing); } /** - * Handle the given exception. + * Register a renderable callback. * - * @param \Exception $exception - * @param bool $fromConsole + * @param callable $renderUsing + * @return $this */ - protected function callCustomHandlers($exception, $fromConsole = false) + public function renderable(callable $renderUsing) { - if ($exception instanceof HttpExceptionInterface) { - $code = $exception->getStatusCode(); - } - - // If the exception doesn't implement the HttpExceptionInterface, we will just - // use the generic 500 error code for a server side error. If it implements - // the HttpException interfaces we'll grab the error code from the class. - else { - $code = 500; - } - - foreach ($this->handlers as $handler) + if ( ! $renderUsing instanceof Closure) { - // If this exception handler does not handle the given exception, we will just - // go the next one. A handler may type-hint an exception that it handles so - // we can have more granularity on the error handling for the developer. - if (! $this->handlesException($handler, $exception)) { - continue; - } + $renderUsing = Closure::fromCallable($renderUsing); + } - $response = $handler($exception, $code, $fromConsole); + $this->renderCallbacks[] = $renderUsing; - // If this handler returns a "non-null" response, we will return it so it will - // get sent back to the browsers. Once the handler returns a valid response - // we will cease iterating through them and calling these other handlers. - if (isset($response) && ! is_null($response)) - { - return $response; - } - } + return $this; } /** - * Display the given exception to the user. + * Indicate that the given exception type should not be reported. * - * @param \Exception $exception + * @param array|string $exceptions + * @return $this */ - protected function displayException($exception) + public function dontReport(array|string $exceptions) { - $displayer = $this->debug ? $this->debugDisplayer : $this->plainDisplayer; + $this->dontReport = array_values(array_unique(array_merge($this->dontReport, Arr::wrap($exceptions)))); - if (! $exception instanceof \Exception) { - if ($exception instanceof \ParseError) { - $severity = \E_PARSE; - } elseif ($exception instanceof \TypeError) { - $severity = \E_RECOVERABLE_ERROR; - } else { - $severity = \E_ERROR; - } + return $this; + } - $exception = new ErrorException( - $exception->getMessage(), - $exception->getCode(), - $severity, - $exception->getFile(), - $exception->getLine(), - ); - } + /** + * Remove the given exception class from the list of exceptions that should be ignored. + * + * @param array|string $exceptions + * @return $this + */ + public function stopIgnoring(array|string $exceptions) + { + $exceptions = Arr::wrap($exceptions); - return $displayer->display($exception); + $this->dontReport = array_values(array_diff($this->dontReport, $exceptions)); + + $this->internalDontReport = array_values(array_diff($this->internalDontReport, $exceptions)); + + return $this; } /** - * Determine if the given handler handles this exception. + * Report or log an exception. * - * @param \Closure $handler - * @param \Exception $exception - * @return bool + * @param \Throwable $e + * @return void */ - protected function handlesException(Closure $handler, $exception) + public function report(Throwable $e) { - $reflection = new ReflectionFunction($handler); + if ($this->shouldntReport($e)) return; + + if (Reflector::isCallable($reportCallable = array($e, 'report')) && $this->app->call($reportCallable) !== false) + { + return; + } - return $reflection->getNumberOfParameters() == 0 || $this->hints($reflection, $exception); + foreach ($this->reportCallbacks as $reportCallback) + { + if ($reportCallback->handles($e) && $reportCallback($e) === false) return; + } + + $this->app->make('log')->error($e->getMessage(), array_merge($this->exceptionContext($e), $this->context(), array('exception' => $e))); } /** - * Determine if the given handler type hints the exception. + * Determine if the exception should be reported. * - * @param \ReflectionFunction $reflection - * @param \Exception $exception + * @param \Throwable $e * @return bool */ - protected function hints(ReflectionFunction $reflection, $exception) + public function shouldReport(Throwable $e) { - $parameters = $reflection->getParameters(); - - $expected = $parameters[0]; + return ! $this->shouldntReport($e); + } - $type = $expected->getType(); - if (!$type || $type->isBuiltin()) { - return false; - } + /** + * Determine if the exception is in the "do not report" list. + * + * @param \Throwable $e + * @return bool + */ + protected function shouldntReport(Throwable $e) + { + foreach (array_merge($this->dontReport, $this->internalDontReport) as $type) + { + if ($e instanceof $type) return true; + } - return (new \ReflectionClass($expected->getType()->getName()))->isInstance($exception); + return false; } /** - * Format an exception thrown by a handler. + * Get the default exception context variables for logging. * - * @return string - * @deprecated + * @param \Throwable $e + * @return array */ - protected function formatException(\Throwable $e): string - { - if ($this->debug) - { - $location = $e->getMessage().' in '.$e->getFile().':'.$e->getLine(); + protected function exceptionContext(Throwable $e) + { + return method_exists($e, 'context') ? $e->context() : array(); + } - return 'Error in exception handler: '.$location; + /** + * Get the default context variables for logging. + * + * @return array + */ + protected function context() + { + try { + return array_filter(array('userId' => $this->app['auth']->id())); + } catch (Throwable) { + return array(); } - - return 'Error in exception handler.'; } /** - * Register an application error handler. + * Render an exception into a response. * - * @param \Closure $callback - * @return void + * @param \Illuminate\Http\Request $request + * @param \Throwable $e + * @return \Symfony\Component\HttpFoundation\Response */ - public function error(Closure $callback) + public function render($request, Throwable $e) { - array_unshift($this->handlers, $callback); + if (method_exists($e, 'render') && $response = $e->render($request)) + { + return Router::toResponse($request, $response); + } + + if ($e instanceof Responsable) + { + return $e->toResponse($request); + } + + $e = $this->prepareException($e); + + foreach ($this->renderCallbacks as $renderCallback) + { + foreach ($this->firstClosureParameterTypes($renderCallback) as $type) + { + if (is_a($e, $type)) + { + $response = $renderCallback($e, $request); + + if ( ! is_null($response)) return $this->app->prepareResponse($response); + } + } + } + + if ($e instanceof HttpResponseException) + { + return $e->getResponse(); + } + + return $this->displayException($e); } /** - * Register an application error handler at the bottom of the stack. + * Prepare exception for rendering. * - * @param \Closure $callback - * @return void + * @param \Throwable $e + * @return \Throwable */ - public function pushError(Closure $callback) + protected function prepareException(Throwable $e) { - $this->handlers[] = $callback; + return match (true) { + $e instanceof BackedEnumCaseNotFoundException => new NotFoundHttpException($e->getMessage(), $e), + $e instanceof ModelNotFoundException => new NotFoundHttpException($e->getMessage(), $e), + $e instanceof AuthorizationException && $e->hasStatus() => new HttpException( + $e->status(), $e->response()?->message() ?: (Response::$statusTexts[$e->status()] ?? 'Whoops, looks like something went wrong.'), $e + ), + $e instanceof AuthorizationException && ! $e->hasStatus() => new AccessDeniedHttpException($e->getMessage(), $e), + $e instanceof OriginMismatchException => new HttpException(403, $e->getMessage(), $e), + $e instanceof TokenMismatchException => new HttpException(419, $e->getMessage(), $e), + $e instanceof RequestExceptionInterface => new BadRequestHttpException('Bad request.', $e), + $e instanceof RecordNotFoundException => new NotFoundHttpException('Not found.', $e), + $e instanceof RecordsNotFoundException => new NotFoundHttpException('Not found.', $e), + default => $e, + }; } /** - * Prepare the given response. + * Display the given exception to the user. * - * @param mixed $response - * @return \Illuminate\Http\Response + * @param \Throwable $exception + * @return \Symfony\Component\HttpFoundation\Response */ - protected function prepareResponse($response) + protected function displayException($exception) { - return $this->responsePreparer->prepareResponse($response); + $displayer = $this->debug ? $this->debugDisplayer : $this->plainDisplayer; + + if (! $exception instanceof \Exception) { + if ($exception instanceof \ParseError) { + $severity = \E_PARSE; + } elseif ($exception instanceof \TypeError) { + $severity = \E_RECOVERABLE_ERROR; + } else { + $severity = \E_ERROR; + } + + $exception = new ErrorException( + $exception->getMessage(), + $exception->getCode(), + $severity, + $exception->getFile(), + $exception->getLine(), + ); + } + + return $displayer->display($exception); } /** diff --git a/src/Illuminate/Foundation/Application.php b/src/Illuminate/Foundation/Application.php index 1844d35f..d0ccccae 100755 --- a/src/Illuminate/Foundation/Application.php +++ b/src/Illuminate/Foundation/Application.php @@ -16,7 +16,6 @@ use Illuminate\Routing\RoutingServiceProvider; use Illuminate\Exception\ExceptionServiceProvider; use Illuminate\Config\FileEnvironmentVariablesLoader; -use Symfony\Component\ErrorHandler\Error\FatalError; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\TerminableInterface; use Symfony\Component\HttpKernel\Exception\HttpException; @@ -1117,56 +1116,6 @@ public function abort($code, $message = '', array $headers = array()) throw new HttpException($code, $message, null, $headers); } - /** - * Register a 404 error handler. - * - * @param \Closure $callback - * @return void - */ - public function missing(Closure $callback) - { - $this->error(function(NotFoundHttpException $e) use ($callback) - { - return call_user_func($callback, $e); - }); - } - - /** - * Register an application error handler. - * - * @param \Closure $callback - * @return void - */ - public function error(Closure $callback) - { - $this['exception']->error($callback); - } - - /** - * Register an error handler at the bottom of the stack. - * - * @param \Closure $callback - * @return void - */ - public function pushError(Closure $callback) - { - $this['exception']->pushError($callback); - } - - /** - * Register an error handler for fatal errors. - * - * @param \Closure $callback - * @return void - */ - public function fatal(Closure $callback) - { - $this->error(function(FatalError $e) use ($callback) - { - return call_user_func($callback, $e); - }); - } - /** * Get the configuration loader instance. * diff --git a/src/Illuminate/Foundation/Configuration/Exceptions.php b/src/Illuminate/Foundation/Configuration/Exceptions.php new file mode 100644 index 00000000..2c749417 --- /dev/null +++ b/src/Illuminate/Foundation/Configuration/Exceptions.php @@ -0,0 +1,76 @@ +handler->reportable($using); + } + + /** + * Register a renderable callback. + * + * @param callable $using + * @return $this + */ + public function render(callable $using) + { + $this->handler->renderable($using); + + return $this; + } + + /** + * Indicate that the given exception type should not be reported. + * + * @param array|string $class + * @return $this + */ + public function dontReport(array|string $class) + { + foreach (Arr::wrap($class) as $exceptionClass) + { + $this->handler->dontReport($exceptionClass); + } + + return $this; + } + + /** + * Do not ignore the given exceptions classes. + * + * @param array|string $class + * @return $this + */ + public function stopIgnoring(array|string $class) + { + $this->handler->stopIgnoring($class); + + return $this; + } + +} diff --git a/src/Illuminate/Foundation/Console/TinkerCommand.php b/src/Illuminate/Foundation/Console/TinkerCommand.php index f55da969..13e3eeaa 100755 --- a/src/Illuminate/Foundation/Console/TinkerCommand.php +++ b/src/Illuminate/Foundation/Console/TinkerCommand.php @@ -63,7 +63,7 @@ protected function setupBorisErrorHandling() $this->laravel->make('artisan')->setCatchExceptions(false); - $this->laravel->error(function() { return ''; }); + $this->laravel['exception']->renderable(function(\Throwable $e) { return ''; }); } /** diff --git a/src/Illuminate/Foundation/Exceptions/ReportableHandler.php b/src/Illuminate/Foundation/Exceptions/ReportableHandler.php new file mode 100644 index 00000000..ed0c6c9e --- /dev/null +++ b/src/Illuminate/Foundation/Exceptions/ReportableHandler.php @@ -0,0 +1,81 @@ +callback = $callback; + } + + /** + * Invoke the handler. + * + * @param \Throwable $e + * @return bool + */ + public function __invoke(Throwable $e) + { + $result = call_user_func($this->callback, $e); + + if ($result === false) return false; + + return ! $this->shouldStop; + } + + /** + * Determine if the callback handles the given exception. + * + * @param \Throwable $e + * @return bool + */ + public function handles(Throwable $e) + { + foreach ($this->firstClosureParameterTypes($this->callback) as $type) + { + if (is_a($e, $type)) return true; + } + + return false; + } + + /** + * Indicate that report handling should stop after invoking this callback. + * + * @return $this + */ + public function stop() + { + $this->shouldStop = true; + + return $this; + } + +} diff --git a/tests/Exception/HandlerTest.php b/tests/Exception/HandlerTest.php index cd4d5278..cdb960c2 100644 --- a/tests/Exception/HandlerTest.php +++ b/tests/Exception/HandlerTest.php @@ -1,16 +1,25 @@ assertSame(0, $error->getCode(), 'error handler should use 0 exception code'); } - #[WithoutErrorHandler] public function testHandleErrorOptionalArguments(): void { @@ -55,166 +64,259 @@ public function testHandleErrorOptionalArguments(): void } #[Test] - public function handleExceptions(): void + public function renderCallbacksRunInRegistrationOrder(): void { $handler = $this->getHandler(); + $handler->renderable(fn (Throwable $e) => new Response('any', 500)); + $handler->renderable(fn (NotFoundHttpException $e) => new Response('missing', 404)); - $handler->error(function(BindingResolutionException $exception, $code, $fromConsole) { - return new JsonResponse([ - 'from_console' => $fromConsole, - 'message' => $exception->getMessage() - ], $code); - }); - - $response = $handler->handleException(new BindingResolutionException("not resolved", 111)); + $response = $handler->render($this->app['request'], new NotFoundHttpException('not found')); - self::assertEquals(500, $response->getStatusCode()); - self::assertJsonStringEqualsJsonString('{"from_console":false,"message":"not resolved"}', $response->getContent()); + self::assertSame('any', $response->getContent()); } #[Test] - public function handlingHttpException(): void + public function aCallbackReturningNullPassesToTheNextOne(): void { $handler = $this->getHandler(); + $handler->renderable(fn (NotFoundHttpException $e) => null); + $handler->renderable(fn (NotFoundHttpException|AccessDeniedHttpException $e) => new Response('missing', $e->getStatusCode())); - $handler->error(function(NotFoundHttpException $exception, $code, $fromConsole) use (&$exceptionCaught) { - return new JsonResponse([ - 'from_console' => $fromConsole, - 'message' => $exception->getMessage() - ], $code); - }); + $response = $handler->render($this->app['request'], new NotFoundHttpException('not found')); + + self::assertSame(404, $response->getStatusCode()); + self::assertSame('missing', $response->getContent()); + } - $response = $handler->handleException(new NotFoundHttpException("not found")); + #[Test] + public function callbacksSeeTheExceptionAfterPrepareException(): void + { + $handler = $this->getHandler(); + $handler->renderable(fn (NotFoundHttpException $e) => new Response(get_class($e->getPrevious()), 404)); + $handler->renderable(fn (HttpException $e) => new Response(get_class($e->getPrevious()), $e->getStatusCode())); - self::assertEquals(404, $response->getStatusCode()); - self::assertJsonStringEqualsJsonString('{"from_console":false,"message":"not found"}', $response->getContent()); + $missing = $handler->render($this->app['request'], new ModelNotFoundException('no model')); + $expired = $handler->render($this->app['request'], new TokenMismatchException('expired')); + + self::assertSame(ModelNotFoundException::class, $missing->getContent()); + self::assertSame(404, $missing->getStatusCode()); + self::assertSame(TokenMismatchException::class, $expired->getContent()); + self::assertSame(419, $expired->getStatusCode()); } #[Test] - public function whenVeryBasicHandlerIsUsedButTypeHintedHandlerReturnsResponse(): void + public function callbacksGetTheRequest(): void { $handler = $this->getHandler(); + $handler->renderable(fn (Throwable $e, Request $request) => new JsonResponse(array('path' => $request->path()))); - $handler->error(function(Throwable $throwable, $code, $fromConsole) { - return new JsonResponse([ - 'from_console' => $fromConsole, - 'message' => $throwable->getMessage() - ], 500); - }); + $response = $handler->render(Request::create('/things/1'), new DomainException('nope')); - $handler->error(function(NotFoundHttpException $exception, $code, $fromConsole) { - return new JsonResponse([ - 'from_console' => $fromConsole, - 'message' => $exception->getMessage() - ], $code); - }); + self::assertSame('{"path":"things\/1"}', $response->getContent()); + } - $response = $handler->handleException(new NotFoundHttpException("not found")); + #[Test] + public function anHttpResponseExceptionWithoutACallbackReturnsItsResponse(): void + { + $response = $this->getHandler()->render($this->app['request'], new HttpResponseException(new Response('stop', 422))); - self::assertEquals(404, $response->getStatusCode()); - self::assertJsonStringEqualsJsonString('{"from_console":false,"message":"not found"}', $response->getContent()); + self::assertSame(422, $response->getStatusCode()); } #[Test] - public function whenBasicErrorHandlerIsUsed(): void + public function withoutACallbackResponseTheDebugDisplayerRenders(): void { $handler = $this->getHandler(); + $handler->renderable(fn (BindingResolutionException $e) => null); - $handler->error(function(Throwable $throwable, $code, $fromConsole) { - return new JsonResponse([ - 'from_console' => $fromConsole, - 'message' => 'Error' - ], 500); - }); + $handler->handleException(new BindingResolutionException('not found')); + + $this->debugDisplayer->display(Argument::type(BindingResolutionException::class))->shouldBeCalledOnce(); + $this->plainDisplayer->display(Argument::cetera())->shouldNotBeCalled(); + } + + #[Test] + public function withoutACallbackResponseInProductionThePlainDisplayerRenders(): void + { + $handler = $this->getHandler(self::DEBUG_DISABLED); - $handler->error(function(NotFoundHttpException $exception, $code, $fromConsole) { - return new JsonResponse([ - 'from_console' => $fromConsole, - 'message' => $exception->getMessage() - ], $code); + $handler->handleException(new BindingResolutionException('not found')); + + $this->debugDisplayer->display(Argument::cetera())->shouldNotBeCalled(); + $this->plainDisplayer->display(Argument::type(BindingResolutionException::class))->shouldBeCalledOnce(); + } + + #[Test] + public function aThrowingCallbackIsDisplayed(): void + { + $handler = $this->getHandler(self::DEBUG_DISABLED); + $handler->renderable(function (BindingResolutionException $e) { + throw new DomainException('Nooo'); }); - $response = $handler->handleException(new BindingResolutionException("not found")); + $handler->handleException(new BindingResolutionException('not found')); - self::assertEquals(500, $response->getStatusCode()); - self::assertJsonStringEqualsJsonString('{"from_console":false,"message":"Error"}', $response->getContent()); + $this->plainDisplayer->display(Argument::type(DomainException::class))->shouldBeCalledOnce(); } #[Test] - public function whenHandlerDoesNotReturnResponse(): void + public function handleExceptionReportsThenRendersForTheCurrentRequest(): void { $handler = $this->getHandler(); + $handler->renderable(fn (Throwable $e, Request $request) => new Response($request->path(), 500)); - $handler->error(function(BindingResolutionException $exception, $code, $fromConsole) { - return; - }); + $response = $handler->handleException(new DomainException('boom')); + + self::assertSame('hello', $response->getContent()); + self::assertSame(array(array('boom', DomainException::class)), $this->log->logged()); + } - $handler->handleException(new BindingResolutionException("not found")); + #[Test] + public function reportLogsTheExceptionWithItsMessage(): void + { + $this->getHandler()->report($exception = new DomainException('boom')); - $this->debugDisplayer->display(Argument::type(BindingResolutionException::class))->shouldBeCalledOnce(); - $this->plainDisplayer->display(Argument::cetera())->shouldNotBeCalled(); + self::assertSame(array(array('boom', DomainException::class)), $this->log->logged()); + self::assertSame($exception, $this->log->entries[0][1]['exception']); } #[Test] - public function whenHandlerDoesNotReturnResponseInProduction(): void + public function internalDontReportTypesAreNotReportedUntilStopIgnoring(): void { - $handler = $this->getHandler(self::DEBUG_DISABLED); + $handler = $this->getHandler(); - $handler->error(function(BindingResolutionException $exception, $code, $fromConsole) { - return; - }); + $handler->report(new NotFoundHttpException('missing')); + $handler->report(new TokenMismatchException('expired')); + self::assertSame(array(), $this->log->logged()); - $handler->handleException(new BindingResolutionException("not found")); + $handler->stopIgnoring(HttpException::class); + $handler->report(new NotFoundHttpException('missing')); + self::assertSame(array(array('missing', NotFoundHttpException::class)), $this->log->logged()); + self::assertFalse($handler->shouldReport(new TokenMismatchException('expired'))); + } - $this->debugDisplayer->display(Argument::cetera())->shouldNotBeCalled(); - $this->plainDisplayer->display(Argument::type(BindingResolutionException::class))->shouldBeCalledOnce(); + #[Test] + public function dontReportSkipsTheTypeAndItsSubclasses(): void + { + $handler = $this->getHandler(); + $handler->dontReport(array(LogicException::class)); + + $handler->report(new DomainException('boom')); + $handler->report(new RuntimeException('kept')); + + self::assertSame(array(array('kept', RuntimeException::class)), $this->log->logged()); } #[Test] - public function whenHandlerThrows(): void + public function reportCallbacksRunInOrderAndFalseStopsReporting(): void { $handler = $this->getHandler(); + $seen = array(); + $handler->reportable(function (DomainException $e) use (&$seen) { $seen[] = 'domain'; }); + $handler->reportable(function (Throwable $e) use (&$seen) { $seen[] = 'any'; return false; }); + $handler->reportable(function (Throwable $e) use (&$seen) { $seen[] = 'never'; }); - $handler->error(function(BindingResolutionException $exception, $code, $fromConsole) { - throw new DomainException('Nooo'); - }); + $handler->report(new DomainException('boom')); + $handler->report(new RuntimeException('other')); - $handler->handleException(new BindingResolutionException("not found")); + self::assertSame(array('domain', 'any', 'any'), $seen); + self::assertSame(array(), $this->log->logged()); + } - $this->debugDisplayer->display(Argument::type(DomainException::class))->shouldBeCalledOnce(); - $this->plainDisplayer->display(Argument::cetera())->shouldNotBeCalled(); + #[Test] + public function aStoppedReportCallbackEndsReportingAfterItRuns(): void + { + $handler = $this->getHandler(); + $seen = array(); + $handler->reportable(function (Throwable $e) use (&$seen) { $seen[] = 'first'; })->stop(); + $handler->reportable(function (Throwable $e) use (&$seen) { $seen[] = 'second'; }); + + $handler->report(new DomainException('boom')); + + self::assertSame(array('first'), $seen); + self::assertSame(array(), $this->log->logged()); } #[Test] - public function whenHandlerThrowsInProduction(): void + public function anExceptionsOwnReportMethodReplacesTheDefaultReport(): void { - $handler = $this->getHandler(self::DEBUG_DISABLED); + $this->getHandler()->report($exception = new HandlerTestSelfReportingException('boom')); - $handler->error(function(BindingResolutionException $exception, $code, $fromConsole) { - throw new DomainException('Nooo'); - }); + self::assertTrue($exception->reported); + self::assertSame(array(), $this->log->logged()); + } + + #[Test] + public function exceptionsConfigurationRegistersOnTheHandler(): void + { + $handler = $this->getHandler(); + $exceptions = new Exceptions($handler); - $handler->handleException(new BindingResolutionException("not found")); + $exceptions->dontReport(DomainException::class)->stopIgnoring(HttpException::class); + $exceptions->render(fn (Throwable $e) => new Response('rendered', 500)); + $exceptions->report(function (Throwable $e) { return false; }); - $this->debugDisplayer->display(Argument::cetera())->shouldNotBeCalled(); - $this->plainDisplayer->display(Argument::type(DomainException::class))->shouldBeCalledOnce(); + self::assertFalse($handler->shouldReport(new DomainException('boom'))); + self::assertTrue($handler->shouldReport(new NotFoundHttpException('missing'))); + self::assertSame('rendered', $handler->render($this->app['request'], new RuntimeException('x'))->getContent()); + $handler->report(new RuntimeException('x')); + self::assertSame(array(), $this->log->logged()); } - protected function getHandler(bool $debug = true): Handler + #[Test] + public function theWorkerAdapterReportsAndRendersThroughTheHandler(): void { - $this->responsePreparer = $this->prophesize(ResponsePreparerInterface::class); + $handler = $this->getHandler(); + $handler->renderable(fn (Throwable $e) => new Response('rendered', 500)); + $adapter = new ExceptionHandlerAdapter($handler); + + $adapter->report(new DomainException('boom')); + + self::assertSame(array(array('boom', DomainException::class)), $this->log->logged()); + self::assertFalse($adapter->shouldReport(new NotFoundHttpException('missing'))); + self::assertSame('rendered', $adapter->render($this->app['request'], new DomainException('boom'))->getContent()); + } + + protected function getHandler(bool $debug = self::DEBUG_ENABLED): Handler + { + $this->app = new Application; + $this->app->instance('request', Request::create('/hello')); + $this->app->instance('log', $this->log = new HandlerTestLogger); $this->plainDisplayer = $this->prophesize(ExceptionDisplayerInterface::class); $this->debugDisplayer = $this->prophesize(ExceptionDisplayerInterface::class); - - $this->responsePreparer->prepareResponse(Argument::cetera())->will(function($args) { - return $args[0]; - }); + $this->plainDisplayer->display(Argument::cetera())->willReturn(new Response('plain', 500)); + $this->debugDisplayer->display(Argument::cetera())->willReturn(new Response('debug', 500)); return new Handler( - $this->responsePreparer->reveal(), + $this->app, $this->plainDisplayer->reveal(), $this->debugDisplayer->reveal(), $debug ); } } + +class HandlerTestLogger +{ + public $entries = array(); + + public function error($message, array $context = array()) + { + $this->entries[] = array($message, $context); + } + + public function logged() + { + return array_map(fn ($entry) => array($entry[0], get_class($entry[1]['exception'])), $this->entries); + } +} + +class HandlerTestSelfReportingException extends Exception +{ + public $reported = false; + + public function report() + { + $this->reported = true; + } +} diff --git a/tests/Queue/QueueForkBridgeTest.php b/tests/Queue/QueueForkBridgeTest.php index 6ac80594..6c955006 100644 --- a/tests/Queue/QueueForkBridgeTest.php +++ b/tests/Queue/QueueForkBridgeTest.php @@ -69,7 +69,7 @@ public function testWorkerCommandReportsFailedJobsThroughTheForkHandler() { $exception = new RuntimeException('job failed'); $handler = $this->prophesize(Handler::class); - $handler->handleConsole($exception)->shouldBeCalledOnce(); + $handler->report($exception)->shouldBeCalledOnce(); $app = $this->makeApplication(); $app->instance('exception', $handler->reveal());