Skip to content

[READ ONLY] Swoft errors for cool kids by filp/whoops

License

Notifications You must be signed in to change notification settings

swoft-cloud/swoft-whoops

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Swoft Whoops

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.