This commit is contained in:
2021-08-04 15:17:25 +08:00
parent e227fd0729
commit c2a974a58e
3 changed files with 79 additions and 3 deletions
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace Server;
use Server\Constrict\Response;
use Server\Constrict\Response as CResponse;
/**
*
*/
class ExceptionHandlerDispatcher implements ExceptionHandlerInterface
{
/**
* @param \Throwable $exception
* @param CResponse $response
* @return Response
*/
public function emit(\Throwable $exception, Response $response): Response
{
$code = $exception->getCode() == 0 ? 500 : $exception->getCode();
$data = $code == 404 ? $exception->getMessage() : jTraceEx($exception, null, true);
return $response->setContent($data)
->setFormat(CResponse::HTML)
->setStatusCode($code);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace Server;
use Server\Constrict\Response;
/**
*
*/
interface ExceptionHandlerInterface
{
/**
* @param \Throwable $exception
* @param Response $response
* @return Response
*/
public function emit(\Throwable $exception, Response $response): Response;
}
+28 -3
View File
@@ -8,9 +8,14 @@ use HttpServer\Exception\RequestException;
use HttpServer\Http\Request as HSRequest;
use HttpServer\Route\Node;
use HttpServer\Route\Router;
use ReflectionException;
use Server\Constrict\Response as CResponse;
use Server\Events\OnAfterRequest;
use Snowflake\Abstracts\Config;
use Snowflake\Events\EventDispatch;
use Snowflake\Exception\ConfigException;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
use Swoole\Error;
use Swoole\Http\Request;
use Swoole\Http\Response;
@@ -45,6 +50,28 @@ class HTTPServerListener extends Abstracts\Server
public EventDispatch $eventDispatch;
/**
* @var ExceptionHandlerInterface
*/
public ExceptionHandlerInterface $exceptionHandler;
/**
* @throws ReflectionException
* @throws ConfigException
* @throws NotFindClassException
*/
public function init()
{
$exceptionHandler = Config::get('exception.http', ExceptionHandlerDispatcher::class);
if (!($exceptionHandler instanceof ExceptionHandlerInterface)){
$exceptionHandler = Snowflake::getDi()->get(ExceptionHandlerDispatcher::class);
}
$this->exceptionHandler = $exceptionHandler;
}
/**
* UDPServerListener constructor.
* @param Server|Port $server
@@ -97,9 +124,7 @@ class HTTPServerListener extends Abstracts\Server
}
$responseData = $this->response->setContent($node->dispatch())->setStatusCode(200);
} catch (Error | Throwable $exception) {
$code = $exception->getCode() == 0 ? 500 : $exception->getCode();
$data = $code == 404 ? $exception->getMessage() : jTraceEx($exception,null,true);
$responseData = $this->response->setContent($data)->setFormat(CResponse::HTML)->setStatusCode($code);
$responseData = $this->exceptionHandler->emit($exception, $this->response);
} finally {
$response->end($responseData->configure($response)->getContent());