| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- <?php
- declare(strict_types=1);
- /**
- * This file is part of Hyperf.
- *
- * @link https://www.hyperf.io
- * @document https://hyperf.wiki
- * @contact group@hyperf.io
- * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
- */
- namespace App\Exception\Handler;
- use Hyperf\Contract\StdoutLoggerInterface;
- use Hyperf\ExceptionHandler\ExceptionHandler;
- use Hyperf\ExceptionHandler\Formatter\FormatterInterface;
- use Hyperf\HttpMessage\Stream\SwooleStream;
- use Psr\Http\Message\ResponseInterface;
- use Throwable;
- use Hyperf\Utils\Str;
- class AppExceptionHandler extends ExceptionHandler
- {
- /**
- * @var StdoutLoggerInterface
- */
- protected $logger;
- /**
- * @var FormatterInterface
- */
- protected $formatter;
- public function __construct(StdoutLoggerInterface $logger, FormatterInterface $formatter)
- {
- $this->logger = $logger;
- $this->formatter = $formatter;
- }
- public function handle(Throwable $throwable, ResponseInterface $response)
- {
- $message = $throwable->getMessage();
- $arrSrace = $throwable->getTrace();
- $strTrace = $throwable->getTraceAsString();
- $code = $throwable->getCode();
- $this->logger->error(sprintf('%s[%s] in %s', $message, $throwable->getLine(), $throwable->getFile()));
- $this->logger->error($strTrace);
- $clientRequest = request();
- $headerContentType = $clientRequest->header('content-type');
- if (!empty($headerContentType) && Str::contains($headerContentType, ['/json', '+json'])) {
- // 是Json请求.
- // 格式化输出.
- $data = [
- 'code' => $code,
- 'array_trace' => $arrSrace,
- 'string_trace' => $strTrace,
- ];
- if (env('APP_ENV', 'prod') == 'prod') {
- $message = '内部错误';
- $data = [];
- }
- return json_fail($message, 500, $data);
- } else {
- return $response->withStatus(500)->withBody(new SwooleStream('内部错误.'));
- }
- }
- public function isValid(Throwable $throwable): bool
- {
- return true;
- }
- }
|