PHPackages                             tinywan/think-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. [Debugging &amp; Profiling](/categories/debugging)
4. /
5. tinywan/think-exception

ActiveLibrary[Debugging &amp; Profiling](/categories/debugging)

tinywan/think-exception
=======================

ThinkPHP 6.0 exception plugin

v1.5.6(7mo ago)51831MITPHPPHP &gt;=7.2

Since Sep 17Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/Tinywan/think-exception)[ Packagist](https://packagist.org/packages/tinywan/think-exception)[ RSS](/packages/tinywan-think-exception/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (4)Versions (28)Used By (0)

ThinkPHP6.0 exception 异常插件
==========================

[](#thinkphp60-exception-异常插件)

[![Total Downloads](https://camo.githubusercontent.com/e51839610e12f6ec99a562d505ec8f9983635ed262500b772b3d0734cfc0d08e/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d657863657074696f6e2f646f776e6c6f616473)](https://packagist.org/packages/tinywan/think-exception)[![Daily Downloads](https://camo.githubusercontent.com/e70fda50f64310bdbe19e8b161ec4d3db8e8e6547359c681d931fdd154762174/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d657863657074696f6e2f642f6461696c79)](https://packagist.org/packages/tinywan/think-exception)[![License](https://camo.githubusercontent.com/8aceafdfca1e7a22723786fa114736fbc9825244c9459b79f31cff4e5ca7014c/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d657863657074696f6e2f6c6963656e7365)](https://packagist.org/packages/tinywan/think-exception)[![PHP Version Require](https://camo.githubusercontent.com/ab1d182cd8e87f118a24f86a0ba8a2d8f15c5f34b3849e7267c48f678b9051f6/687474703a2f2f706f7365722e707567782e6f72672f74696e7977616e2f7468696e6b2d657863657074696f6e2f726571756972652f706870)](https://packagist.org/packages/tinywan/think-exception)![exception-handler](https://camo.githubusercontent.com/82525c8a21cec2a88e5719b47ac1d8f03351f2e8be703d7dd765ab6f71dc013c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f74696e7977616e2f7468696e6b2d657863657074696f6e2f6d61696e)![exception-handler](https://camo.githubusercontent.com/04ffdfa05f657a18602a4e78211c36615ab5f32d98e3263526b6c5db1e5cdc5f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f7461672f74696e7977616e2f7468696e6b2d657863657074696f6e3f636f6c6f723d666636396234)

安装
--

[](#安装)

```
composer require tinywan/think-exception

```

配置
--

[](#配置)

### 发布配置

[](#发布配置)

```
php think tinywan:exception

```

这将自动生成 `config/exception.php` 配置文件。

### 配置异常类

[](#配置异常类)

日志服务 `app/provider.php`

```
return [
    'think\exception\Handle' => tinywan\Handler::class,
];
```

日志订阅 `app/event.php`

```
return [
    // 添加一个订阅类
    'subscribe' => [
        \tinywan\subscribe\ExceptionSubscribe::class,
    ],
];
```

基本用法
----

[](#基本用法)

请求参数错误

```
use tinywan\exception\BadRequestHttpException;

class Token {
    public function issueToken(Request $request): Response
    {
        $params = $request->post();
        if (empty($params)) {
            throw new BadRequestHttpException('账号或密码不能为空');
        }
    }
}
```

以上异常抛出错误信息，如下格式：

```
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=utf-8

{
    "code": 0,
    "msg": "账号或密码不能为空",
    "data": {},
}
```

> 所有返回的异常信息将以json格式返回，以上为`返回简略的异常信息`

所有的异常错误处理器根据配置文件 `config/app.php`中`debug`的值来调整错误显示， 当`debug`值为`true` (表示在调试模式)， 错误处理器会显示异常以及详细的函数调用栈和源代码行数来帮助调试，将返回详细的异常信息。 当`debug`值为`false`，只有错误信息会被显示以防止应用的敏感信息泄漏，将返回简略的异常信息。

返回详细的异常信息

```
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=utf-8

{
    "code": 0,
    "msg": "password不允许为空",
    "data": {
        "request_url": "POST //127.0.0.1:8888/oauth/issue-token",
        "timestamp": "2022-03-06 15:19:12",
        "client_ip": "172.18.0.1",
        "request_param": {
            "username": "webman"
        },
        "error_message": "password不允许为空",
        "error_trace": "#0 /var/www/tinywan-admin/app/functions.php(68): Tinywan\\Validate\\Validate->check(Array)\n#1 /var/www/webman-admin/app/controller/Authentication.php(25): validate(Array, 'app\\\\common\\\\vali...')\n#2 /var/www/webman-admin/vendor/workerman/webman-framework/src/App.php(234): app\\controller\\Authentication->issueToken(Object(support\\Request))\n#3 /var/www/webman-admin/app/middleware/AccessControlMiddleware.php(26): Webman\\App::Webman\\{closure}(Object(support\\Request))\n#4 /var/www/webman-admin/vendor/workerman/webman-framework/src/App.php(228): app\\middleware\\AccessControlMiddleware->process(Object(support\\Request), Object(Closure))\n#5 /var/www/webman-admin/vendor/workerman/webman-framework/src/App.php(137): Webman\\App::Webman\\{closure}(Object(support\\Request))\n#6 /var/www/webman-admin/vendor/workerman/workerman/Connection/TcpConnection.php(638): Webman\\App->onMessage(Object(Workerman\\Connection\\TcpConnection), Object(support\\Request))\n#7 /var/www/webman-admin/vendor/workerman/workerman/Events/Select.php(295): Workerman\\Connection\\TcpConnection->baseRead(Resource id #254)\n#8 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(2417): Workerman\\Events\\Select->loop()\n#9 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(1541): Workerman\\Worker->run()\n#10 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(1383): Workerman\\Worker::forkOneWorkerForLinux(Object(Workerman\\Worker))\n#11 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(1357): Workerman\\Worker::forkWorkersForLinux()\n#12 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(549): Workerman\\Worker::forkWorkers()\n#13 /var/www/webman-admin/start.php(87): Workerman\\Worker::runAll()\n#14 {main}"
    }
}
```

自定义异常 Response
--------------

[](#自定义异常-response)

只支持修改`body`的三个字段的key值。必须保持顺序是：

- ① 状态码
- ② 错误消息
- ③ 响应数据

> 使用场景

- 每个项目有标准的统一输出，自定义返回内容
- 前后端分离：前端要求返回的 `HTTP状态码`并不是 `429`，而是 `200` 或者其他
- 响应的`body`不是 `{"code":0,"msg":"Too Many Requests"}`，而是 `{"error_code":200,"message":"Too Many Requests"}` 等其他内容

### 自定义HTTP状态码

[](#自定义http状态码)

编辑 `config/exception.php` 文件的 `status` HTTP 状态码

### 自定义`body`返回内容

[](#自定义body返回内容)

编辑 `config/exception.php` 文件的 `body` 的字段

**默认选项是**

```
{
	"code": 0,
	"msg": "Too Many Requests",
	"data": null
}
```

**自定义选项参考一**

1、假设`status` HTTP 状态码设置为 `200`

2、假设`body`的数组设为为

```
'body' => [
	'error_code' => 200,
	'message' => '请求太多请稍后重试'
]
```

则响应内容为

```
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8

{
	"error_code": 200,
	"message": "请求太多请稍后重试"
}
```

其他的可以根据自身业务自定义即可

扩展自己的 Handler
-------------

[](#扩展自己的-handler)

当项目需要自定义情况比较多的时候，很可能需要扩展 Handler，此时可以继承 `tinywan\Handler` 然后修改对应方法即可。

> 使用场景

- response需要响应`xml`，而不是json格式，只需要覆盖`buildResponse`方法
- 扩展其他Exception的响应，我只要覆盖`solveExtraException`
- 要异常推送微信消息，我可以覆盖`triggerNotifyEvent`

自定义异常 `ErrorHandler`

```
namespace app\common;

use Throwable;
use tinywan\Handler;

class ErrorHandler extends Handler
{
    /**
     * @desc: 重写处理扩展的异常，增加自己的异常
     * @param Throwable $e
     * @author Tinywan(ShaoBo Wan)
     */
    protected function solveExtraException(Throwable $e): void
    {
        // 用户中心异常处理
        if ($e instanceof \ErrorException) {
            $this->errorMessage = '用户中心异常：'.$e->getMessage();
            $this->errorCode = 400;
            return;
        }
        parent::solveExtraException($e);
    }
}
```

异常通知（钉钉机器人）
-----------

[](#异常通知钉钉机器人)

[![dingtalk.png](dingtalk.png)](dingtalk.png)

自定义异常消息

```
$message = ' - 自定义错误1： 浏览器版本xxx'. " \n";
$message .= ' - 自定义错误2： 浏览器版本xxx'. " \n";
\tinywan\event\NotifyEvent::dingTalkRobot([], [], '正式', $message);
```

Other
-----

[](#other)

### phpstan

[](#phpstan)

```
vendor/bin/phpstan analyse src

```

### vendor/bin/php-cs-fixer fix src

[](#vendorbinphp-cs-fixer-fix-src)

```
vendor/bin/php-cs-fixer fix src

```

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance64

Regular maintenance activity

Popularity16

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 ~43 days

Total

27

Last Release

216d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b0042e0b68ff6a731ef382a03eecd211736c2d619acc55b2b326988085f72bfb?d=identicon)[Tinywan](/maintainers/Tinywan)

---

Top Contributors

[![Tinywan](https://avatars.githubusercontent.com/u/14959876?v=4)](https://github.com/Tinywan "Tinywan (57 commits)")

---

Tags

composercomposer-libraryexception-handlingexceptionsphpthinkphp6

###  Code Quality

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tinywan-think-exception/health.svg)

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

###  Alternatives

[symfony/stopwatch

Provides a way to profile code

2.8k387.2M918](/packages/symfony-stopwatch)[fruitcake/laravel-debugbar

PHP Debugbar integration for Laravel

19.1k662.9k29](/packages/fruitcake-laravel-debugbar)[spatie/ignition

A beautiful error page for PHP applications.

510147.6M69](/packages/spatie-ignition)[jokkedk/webgrind

Webgrind is a Xdebug profiling web frontend in PHP5. It implements a subset of the features of kcachegrind and installs in seconds and works on all platforms. For quick'n'dirty optimizations it does the job.

3.3k193.0k](/packages/jokkedk-webgrind)[koriym/printo

An object graph visualizer.

1421.8M2](/packages/koriym-printo)[soloterm/dumps

A Laravel command to intercept dumps from your Laravel application.

125285.7k3](/packages/soloterm-dumps)

PHPackages © 2026

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