swoft/whoops

Whoops Component for Swoft

v2.0.11 2021-05-06 16:33 UTC

This package is auto-updated.

Last update: 2024-11-08 00:16:51 UTC


README

Latest Stable Version Php Version Swoft Doc Swoft License

Swoft http errors for cool kids by filp/whoops

Install

  • composer command
composer require --dev swoft/whoops

Usage

  • Method 1

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

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

Change the App\Exception\Handler\HttpExceptionHandler class:

<?php declare(strict_types=1);

namespace App\Exception\Handler;

use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Http\Message\ContentType;
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
     */
    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)->withContentType(ContentType::HTML);;
    }
}

LICENSE

The Component is open-sourced software licensed under the Apache license.