PHPackages                             gzoran/laravel-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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. gzoran/laravel-exception

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

gzoran/laravel-exception
========================

Laravel 异常处理封装

2.0.0(7y ago)28181[1 issues](https://github.com/gzoran/laravel-exception/issues)MITPHP

Since Dec 21Pushed 7y agoCompare

[ Source](https://github.com/gzoran/laravel-exception)[ Packagist](https://packagist.org/packages/gzoran/laravel-exception)[ RSS](/packages/gzoran-laravel-exception/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (4)Versions (6)Used By (0)

Laravel Exception
=================

[](#laravel-exception)

Laravel 异常处理包

[![Build Status](https://camo.githubusercontent.com/4e4e4a307f5a68ec3afc385cb162deabdf02d61e366aa948fbd9bfcb4b65b9ff/68747470733a2f2f7472617669732d63692e6f72672f677a6f72616e2f6c61726176656c2d657863657074696f6e2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/gzoran/laravel-exception)[![StyleCI build status](https://camo.githubusercontent.com/fa518d589972182d2a17ff559aec5132d92417d1c2ba063c6994bc715e5d895c/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3136323636313138312f736869656c64)](https://camo.githubusercontent.com/fa518d589972182d2a17ff559aec5132d92417d1c2ba063c6994bc715e5d895c/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3136323636313138312f736869656c64)

框架要求
----

[](#框架要求)

Laravel &gt;= 5.5

安装
--

[](#安装)

```
composer require "gzoran/laravel-exception:~2.0"
```

发布配置文件
------

[](#发布配置文件)

此命令会在框架 config 目录下生成 exception.php 配置文件。

```
php artisan vendor:publish --provider="Gzoran\Exception\LaravelExceptionProvider"
```

初始化命令
-----

[](#初始化命令)

此命令会在框架 app/Exceptions 目录下生成一个 AppException 和一个包含一些异常处理类的 Handlers 文件夹。

```
php artisan exception:init
```

使用
--

[](#使用)

在框架 app/Exceptions/Handler.php 中使用 ExceptionHandlerTrait 。

```
class Handler extends ExceptionHandler
{
    use ExceptionHandlerTrait;

    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    ···
```

修改 Handler 类的 render 方法如下。

```
···

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    // return parent::render($request, $exception);

    return $this->handlersRender($request, $exception);
}

···
```

配置文件
====

[](#配置文件)

配置 config/exception.php

```
···

// 配置 Exception 子类与对应处理类（Handler）
'handlers' => [
    App\Exceptions\AppException::class => App\Exceptions\Handlers\AppExceptionHandler::class,
],

// 配置 Exception 基类处理类（Handler），在 Exception 子类匹配不到处理类（Handler）时，会使用此处基类的处理类（Handler）
'base_exception_handler' => App\Exceptions\Handlers\ExceptionHandler::class,

// 配置 Api 接口的 url 开始特征，用以在该 url 下强制以接口形式返回。
// 若不配置此项，请求接口时必须声明头部 Content-Type:application/json
// 否则异常将以页面形式返回
'api_starts_with' => [
    '/api'
],

···
```

应用异常类 AppException
------------------

[](#应用异常类-appexception)

更改 app/Exception/AppException.php 以应对你的具体业务

```
class AppException extends Exception
{
    /**
     * 添加你的错误码消息列表
     *
     * @var array
     */
    protected $codeList = [
        '10000' => [
            'message' => '业务错误'
        ],
    ];

    ...
```

然后找个需要的地方抛出异常即可

```
...

// 抛出业务错误，参数：错误码 $code 错误详情 $errors = [] 状态码 $httpStatus = 400
throw new AppException(10000);

...
```

应用异常处理类 AppExceptionHandler
---------------------------

[](#应用异常处理类-appexceptionhandler)

更改 app/Exception/Handlers/AppExceptionHandler.php 以应对你的具体业务

```
/**
 * 返回 API 响应，这里你可以组装你的 API 响应
 *
 * @author Mike
 * @param Request $request
 * @param $exception
 * @return mixed
 */
public function apiRender(Request $request, $exception)
{
    /**
     * @var $exception AppException
     */
    return $this->response($exception->getResponse(), $exception->getHttpStatus());
}

/**
 * 返回页面响应，这里可以根据需要返回你自定义的视图
 *
 * @author Mike
 * @param Request $request
 * @param Exception $exception
 * @return mixed
 */
public function pageRender(Request $request, Exception $exception)
{
    return response(500, 500);
}
```

你也可以生成自己的异常类（Exception）和异常处理类（Handler）
--------------------------------------

[](#你也可以生成自己的异常类exception和异常处理类handler)

生成异常类（Exception），并按业务需求更改，文件路径 app/Exceptions

```
php artisan make:exception FooException
```

生成异常处理类（Handler），并按业务需求更改，文件路径 app/Exceptions/Handles

```
php artisan make:exception_handler FooExceptionHandler
```

然后在 app/config/exception.php 配置异常类（Exception）和异常处理类（Handler）的对应关系

```
...

'handlers' => [
    App\Exceptions\AppException::class => App\Exceptions\Handlers\AppExceptionHandler::class,
    App\Exceptions\FooException::class => App\Exceptions\Handlers\FooExceptionHandler::class,
],

...
```

最后找个需要的地方抛出异常即可

```
...

throw new FooException();

...
```

License
-------

[](#license)

MIT

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance10

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity64

Established project with proven stability

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

Total

4

Last Release

2603d ago

Major Versions

1.0.2 → 2.0.02019-03-27

### Community

Maintainers

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

---

Top Contributors

[![gzoran](https://avatars.githubusercontent.com/u/28888200?v=4)](https://github.com/gzoran "gzoran (9 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/gzoran-laravel-exception/health.svg)

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

###  Alternatives

[overtrue/laravel-query-logger

A dev tool to log all queries for laravel application.

413307.5k6](/packages/overtrue-laravel-query-logger)[guanguans/laravel-exception-notify

Monitor exception and report to the notification channels(Log、Mail、AnPush、Bark、Chanify、DingTalk、Discord、Gitter、GoogleChat、IGot、Lark、Mattermost、MicrosoftTeams、NowPush、Ntfy、Push、Pushback、PushBullet、PushDeer、PushMe、Pushover、PushPlus、QQ、RocketChat、ServerChan、ShowdocPush、SimplePush、Slack、Telegram、WeWork、WPush、XiZhi、YiFengChuanHua、ZohoCliq、ZohoCliqWebHook、Zulip).

14642.7k1](/packages/guanguans-laravel-exception-notify)[regulus/activity-log

A clean and simple Laravel 5 activity logger for monitoring user activity on a website or web application.

164220.1k2](/packages/regulus-activity-log)

PHPackages © 2026

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