diff --git a/config/autoload/exceptions.php b/config/autoload/exceptions.php index 3e19273..d331de6 100644 --- a/config/autoload/exceptions.php +++ b/config/autoload/exceptions.php @@ -1,26 +1,21 @@ [ 'http' => [ - Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class, - ApiExceptionHandler::class, + // HttpExceptionHandler::class, + // ApiExceptionHandler::class, + GlobalExceptionHandler::class, ], 'jsonrpc-http' => [ - Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class, + HttpExceptionHandler::class, RpcExceptionHandler::class, ], ], diff --git a/extend/Aether/PHP/Hyperf/AetherModel.php b/extend/Aether/PHP/Hyperf/AetherModel.php index e614f6c..a828f94 100644 --- a/extend/Aether/PHP/Hyperf/AetherModel.php +++ b/extend/Aether/PHP/Hyperf/AetherModel.php @@ -119,9 +119,8 @@ abstract class AetherModel extends HyperfModel implements CacheableInterface { if (! static::query()->where('id', $id)->exists()) { throw new ModelNotFoundException(sprintf( - '找不到ID为 %d 的 %s 记录', + '找不到 ID 为 %d 的记录', $id, - static::class )); } return static::query()->where('id', $id)->delete() > 0; @@ -155,9 +154,8 @@ abstract class AetherModel extends HyperfModel implements CacheableInterface $record = static::query()->find($id); if (is_null($record)) { throw new ModelNotFoundException(sprintf( - '找不到ID为 %d 的 %s 记录', - $id, - static::class + '找不到 ID 为 %d 的记录', + $id )); } return $record; // static::query()->findOrFail($id); diff --git a/extend/Aether/PHP/Hyperf/Config.php b/extend/Aether/PHP/Hyperf/Config.php new file mode 100644 index 0000000..13536b2 --- /dev/null +++ b/extend/Aether/PHP/Hyperf/Config.php @@ -0,0 +1,14 @@ +logger = $logger; // filter + } + public function handle(Throwable $throwable, ResponseInterface $response): MessageInterface|ResponseInterface { // 处理业务异常 if ($throwable instanceof BusinessException) { $data = [ - 'code' => $throwable->getCode(), - 'message' => $throwable->getMessage(), - 'data' => null, - 'timestamp' => time(), + Config::RESPONSE_FIELD_KEY_CODE => $throwable->getCode(), + Config::RESPONSE_FIELD_KEY_MESSAGE => $throwable->getMessage(), + Config::RESPONSE_FIELD_KEY_DATA => null, + ]; + } + // 数据库无记录异常 + if ($throwable instanceof ModelNotFoundException) { + $data = [ + Config::RESPONSE_FIELD_KEY_CODE => 404, + Config::RESPONSE_FIELD_KEY_MESSAGE => $throwable->getMessage() ?: '没有对应记录', + Config::RESPONSE_FIELD_KEY_DATA => null, ]; } else { // 记录未知错误日志 @@ -36,15 +52,14 @@ class GlobalExceptionHandler extends ExceptionHandler )); $data = [ - 'code' => 500, - 'message' => 'Server internal error', - 'data' => env('APP_ENV') === 'dev' ? [ + Config::RESPONSE_FIELD_KEY_CODE => 500, + Config::RESPONSE_FIELD_KEY_MESSAGE => 'Server internal error', + Config::RESPONSE_FIELD_KEY_DATA => env('APP_ENV') === 'dev' ? [ 'message' => $throwable->getMessage(), 'file' => $throwable->getFile(), 'line' => $throwable->getLine(), 'trace' => $throwable->getTraceAsString(), ] : null, - 'timestamp' => time(), ]; }