hyperf-view/builder/Exception/Handler/AppExceptionHandler.php

58 lines
1.7 KiB
PHP

<?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 Builder\Exception\Handler;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Codec\Json;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Logger\Logger;
use Throwable;
class AppExceptionHandler extends ExceptionHandler
{
protected Logger $logger;
/**
* @var StdoutLoggerInterface
*/
protected StdoutLoggerInterface $console;
public function __construct()
{
$this->console = console();
$this->logger = container()->get(LoggerFactory::class)->get('mineAdmin');
}
public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
{
$this->console->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
$this->console->error($throwable->getTraceAsString());
$this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
$format = [
'success' => false,
'code' => 500,
'message' => $throwable->getMessage()
];
return $response->withHeader('Server', 'MineAdmin')
->withAddedHeader('content-type', 'application/json; charset=utf-8')
->withStatus(500)->withBody(new SwooleStream(Json::encode($format)));
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}