Swoft Whoops

swoft/whoops is a simple wrapper for filp/whoops in swawt to render and display exception messages that are more conducive to reading.

Swoft-whoops

Github

installation

As an additional extension component, swoft/whoops requires manual installation:

  • With the composer command:
 composer require swoft/whoops 
  • Configured by composer.json :
     "swoft/whoops": "~2.0.0" 

use

Used as a middleware

Use Swoft\Whoops\WhoopsMiddleware as a global Http middleware ( app/bean.php ):

     'httpDispatcher'   => [
        // Add global http middleware
        'middlewares' => [
            // Notice: Please add to the first place
            \Swoft\Whoops\WhoopsMiddleware::class,
        ],
    ], 

Note: Add Swoft\Whoops\WhoopsMiddleware to the first location

Used in exception handling

We slightly adjust the default http exception handling class ( App\Exception\Handler\HttpExceptionHandler ):

 <?php declare(strict_types=1);

namespace App\Exception\Handler;

use ReflectionException;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Exception\Handler\AbstractHttpErrorHandler;
use Swoft\Log\Helper\CLog;
use Swoft\Whoops\WhoopsHandler;
use Throwable;
use function bean;
use function context;
use const APP_DEBUG;

/**
 * Class HttpExceptionHandler
 *
 * @ExceptionHandler(\Throwable::class)
 */
class HttpExceptionHandler extends AbstractHttpErrorHandler
{
    /**
     * @param Throwable $e
     * @param Response  $response
     *
     * @return Response
     * @throws ReflectionException
     * @throws ContainerException
     */
    public function handle(Throwable $e, Response $response): Response
    {
        $request = context()->getRequest();
        if ($request->getUriPath() === '/favicon.ico') {
            return $response->withStatus(404);
        }

        // Log
        CLog::error($e->getMessage());

        // Debug is false
        if (!APP_DEBUG) {
            return $response
                ->withStatus(500)
                ->withContent($e->getMessage());
        }

        // Debug is true
        $whoops  = bean(WhoopsHandler::class);
        $content = $whoops->run($e, $request);
        return $response->withContent($content);
    }
} 

Now we restart the http server, and when an exception occurs, we can see the error message page rendered by whoops .

Participate in the contribution

Welcome to participate in the contribution, you can

  • Fork our development warehouse swowt/whoops
  • Modify the code and then initiate the PR
  • About PR launch of Notes
/docs/2.x/en/extra/whoops.html
progress-bar