控制器 app/Controller/IndexController.php
<?php
namespace App\Controller;
use Hyperf\HttpServer\Annotation\AutoController;
use App\Exception\FooException;
/**
* @AutoController();
*/
class IndexController
{
public function index(){
throw new FooException('Foo Exception...', 504);
return 'index';
}
}
定义异常处理器 app/Exception/Handler/FooExceptionHandler.php
<?php
namespace App\Exception\Handler;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use App\Exception\FooException;
use Throwable;
class FooExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponseInterface $response)
{
// 判断被捕获到的异常是希望被捕获的异常
if ($throwable instanceof FooException) {
// 格式化输出
$data = json_encode([
'code' => $throwable->getCode(),
'message' => $throwable->getMessage(),
], JSON_UNESCAPED_UNICODE);
// 阻止异常冒泡
$this->stopPropagation();
return $response->withStatus(500)->withBody(new SwooleStream($data));
}
// 交给下一个异常处理器
return $response;
// 或者不做处理直接屏蔽异常
}
/**
* 判断该异常处理器是否要对该异常进行处理
*/
public function isValid(Throwable $throwable): bool
{
return true;
}
}
定义异常处理类 app/Exception/FooException.php
<?php
namespace App\Exception;
use App\Constants\ErrorCode;
use Hyperf\Server\Exception\ServerException;
use Throwable;
class FooException extends ServerException
{
}
注册异常处理器 config/autoload/exceptions.php
<?php
declare(strict_types=1);
return [
'handler' => [
'http' => [
Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
App\Exception\Handler\AppExceptionHandler::class,
App\Exception\Handler\FooExceptionHandler::class,
],
],
];
测试
curl 118.195.173.53:9501/index/index
结果
{"code":504,"message":"Foo Exception..."}