PHP code example of gzoran / laravel-exception

1. Go to this page and download the library: Download gzoran/laravel-exception library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gzoran / laravel-exception example snippets


class Handler extends ExceptionHandler
{
    use ExceptionHandlerTrait;

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

···

/**
 * 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);
}

···

···

// 配置 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'
],

···


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



...

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

...



/**
 * 返回 API 响应,这里你可以组装你的 API 响应
 * 
 * @author Mike <[email protected]>
 * @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 <[email protected]>
 * @param Request $request
 * @param Exception $exception
 * @return mixed
 */
public function pageRender(Request $request, Exception $exception)
{
    return response(500, 500);
}



...

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

...



...

throw new FooException();

...

shell
php artisan vendor:publish --provider="Gzoran\Exception\LaravelExceptionProvider"
shell
php artisan exception:init
shell

php artisan make:exception FooException

shell

php artisan make:exception_handler FooExceptionHandler