PHPackages                             liuchang103/hyperf-exception - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. liuchang103/hyperf-exception

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

liuchang103/hyperf-exception
============================

hyperf exception api handler

1.1.1(5y ago)23.5k1MITPHPPHP &gt;=7.2

Since Jul 30Pushed 5y ago1 watchersCompare

[ Source](https://github.com/liuchang103/hyperf-exception)[ Packagist](https://packagist.org/packages/liuchang103/hyperf-exception)[ RSS](/packages/liuchang103-hyperf-exception/feed)WikiDiscussions master Synced 4d ago

READMEChangelogDependencies (6)Versions (4)Used By (0)

hyperf-exception
----------------

[](#hyperf-exception)

Hyperf 的异常错误处理，有 Json 和 View 自定义渲染

安装
--

[](#安装)

#### 引入包

[](#引入包)

```
composer require liuchang103/hyperf-exception

```

使用
--

[](#使用)

#### 直接抛出 Json

[](#直接抛出-json)

```
throw new \HyperfException\Json('Error', -1);

// 输出
{"code":-1,"message":"Error"}

```

#### 直接抛出 View 视图

[](#直接抛出-view-视图)

```
throw new \HyperfException\View('Error', '404');

// 将抛出 404 的视图文件

```

进阶
--

[](#进阶)

#### 继承 Json

[](#继承-json)

使用常量约定 code 码，让控制器中消失 “数字”

```
namespace App\Exception;

class Success extends \HyperfException\Json
{
    const CODE = 100;
}

// 抛出
throw new \App\Exception\Success('Created Success');

// 输出
{"code":100,"message":"Created Success"}

```

定义 Http 状态码

```
class Error extends \HyperfException\Json
{
    const CODE = 200;
    const HTTP_STATUS = 500;
}

// 抛出
throw new \App\Exception\Error('Created Error');

// 将抛出 500 的 Http 状态
{"code":200,"message":"Created Error"}

```

定义 json 格式

```
class Error extends \HyperfException\Json
{
    const CODE = -1;
    const HTTP_STATUS = 500;

    // 自定义 json 格式
    protected function json()
    {
        return [
            'errcode' => $this->getCode(),
            'errmessage' => $this->getMessage()
        ];
    }
}

// 抛出
throw new \App\Exception\Error('Created Error');

// 将抛出 500 的 json 格式
{"errcode":-1,"errmessage":"Created Error"}

```

自定义传参

```
class Error extends \HyperfException\Json
{
    const CODE = -1;
    const HTTP_STATUS = 500;

    public function __construct($message, $model)
    {
        parent::__construct($message);

        $this->model = $model;
    }

    // 自定义 json 格式
    protected function json()
    {
        return [
            'errcode' => $this->getCode(),
            'errmessage' => $this->getMessage(),
            'model' => $this->model
        ];
    }
}

// 抛出
throw new \App\Exception\Error('Update Error', $model);

// 将抛出 500 的 json 格式
{"errcode":-1,"errmessage":"Update Error", "model":{}}

```

#### 继承 View

[](#继承-view)

使用常量约定 VIEW，让控制器中消失 “模版名”

```
namespace App\Exception;

class Miss extends \HyperfException\View
{
    const VIEW = '404';
}

// 抛出
throw new \App\Exception\Miss('找不到存在的页面');

// 视图文件 404.blade.php
 {{ $message }}

```

定义 Http 状态码

```
class Miss extends \HyperfException\View
{
    const VIEW = '404';
    const HTTP_STATUS = 404;
}

// 抛出
throw new \App\Exception\Miss('找不到存在的页面');

```

自定义视图传参

```
class Miss extends \HyperfException\View
{
    const VIEW = '404';
    const HTTP_STATUS = 404;

    protected $model;

    public function __construct($message, $model)
    {
        parent::__construct($message);

        $this->model = $model;
    }

    // 自定义视图参数
    protected function view()
    {
        return [
            'model' => $this->model
        ];
    }
}

// 抛出
throw new \App\Exception\Miss('Error', $model);

// 404.blade.php
{{ $model->name }} 访问页面错误

```

自定义处理
-----

[](#自定义处理)

如果需要自定义渲染，可继承 \\HyperfException\\Exception 并实现 render 方法，会接收 response 的对象

```
use HyperfException\Exception;
use Hyperf\HttpMessage\Stream\SwooleStream;

class Message extends Exception
{
    const HTTP_STATUS = 202;

    // 自定义渲染
    public function render($response)
    {
        return $response->withBody(new SwooleStream($this->getMessage() . $this->getCode()));
    }
}

// 抛出
throw new \App\Exception\Message('自定义渲染', 1);

// 输出 202 的状态页面
自定义渲染1

```

HTTP\_STATUS 状态码是在更深一层的自定义处理中.

如果要自定义处理，可实现 handle 方法，同样会接收 response 的对象

(注意：实现 handle 方法后，HTTP\_STATUS 常量将无效，render 渲染方法也将无效)

```
public function handle($response)
{
    return $response->withBody(new SwooleStream($this->getMessage() . $this->getCode()));
}

// 输出 200 正常状态的页面
自定义渲染1

```

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~102 days

Total

3

Last Release

1911d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7370a135b7bbe96c933f049e6d8fc24ab3fd886216dd856f4dacc3bfd578858f?d=identicon)[liuchang103](/maintainers/liuchang103)

---

Top Contributors

[![liuchang103](https://avatars.githubusercontent.com/u/55739415?v=4)](https://github.com/liuchang103 "liuchang103 (7 commits)")

---

Tags

phphyperf

###  Code Quality

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/liuchang103-hyperf-exception/health.svg)

```
[![Health](https://phpackages.com/badges/liuchang103-hyperf-exception/health.svg)](https://phpackages.com/packages/liuchang103-hyperf-exception)
```

###  Alternatives

[hyperf/watcher

Hot reload watcher for Hyperf

17846.7k27](/packages/hyperf-watcher)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
