Commit b8132368 authored by 王源's avatar 王源
Browse files

添加捕获所有未捕获的异常处理文件

parent 981bbae5
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -20,6 +20,7 @@
    "hyperf/redis": "~1.1.0",
    "hyperf/guzzle": "~1.1.0",
    "hyperf/config": "~1.1.0",
    "hyperf/logger": "~1.1.0",
    "hyperf/service-governance": "~1.1.0",
    "fzaninotto/faker": "^1.9"
  },
+1 −0
Original line number Diff line number Diff line
@@ -19,6 +19,7 @@ class ConfigProvider
                    'http' => [
                        \Meibuyu\Micro\Exceptions\Handler\MicroExceptionHandler::class,
                        \Meibuyu\Micro\Exceptions\Handler\QueryExceptionHandler::class,
                        \Meibuyu\Micro\Exceptions\Handler\AppExceptionHandler::class,
                    ],
                ],
            ],
+48 −0
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Meibuyu\Micro\Exceptions\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Logger\LoggerFactory;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Throwable;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $stdoutLogger;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $stdoutLogger, LoggerFactory $loggerFactory)
    {
        $this->stdoutLogger = $stdoutLogger;
        $this->logger = $loggerFactory->get('Uncaught Exception');
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 捕获所有未捕获的异常
        $this->stopPropagation();
        $msg = sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile());
        $this->stdoutLogger->error($msg);
        $this->logger->error($msg);
        $this->stdoutLogger->error($throwable->getTraceAsString());
        return $response->withHeader("Server", "H5Q-OA")->withStatus(500)->withBody(new SwooleStream($msg));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}