PHP code example of liuchang103 / hyperf-exception

1. Go to this page and download the library: Download liuchang103/hyperf-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/ */

    

liuchang103 / hyperf-exception example snippets


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":{}}

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 }} 访问页面错误


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

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