ThinkPHP5的全局异常

 1、修改configuration里面的配置
 
 * 异常处理handle类 留空使用 \think\exception\Handle
    'exception_handle'       => 'app\exception\ExceptionHandler',  //这里是你自己的异常类重写的目录

    <br>

<?php
    /**
     * Created by PhpStorm.
     * User: admin
     * Date: 2018/9/23
     * Time: 22:43
     */
    
    namespace app\exception;
    use think\Exception;
    use think\exception\Handle;
    use think\Log;
    use think\Request;
    
    class ExceptionHandler extends Handle
    {
        private $code;
        private $msg;
        private $errorCode;
            /**继承并重写Exception类
             * @param Exception $ex
             * @return \think\Response|\think\response\Json
             */
        
            public function render(\Exception $ex)
            {
                if ($ex instanceof BaseException) {
                    $this->msg = $ex->code;
                    $this->msg = $ex->msg;
                    $this->errorCode = $ex->errorCode;
        
                } else {
                    if ( config('app_debug') ) {
                        //显示页面错误,用于开发人员内部开发
                     return    parent::render($ex);
                    } else {
        
                        $this->code = 500;
                    $this->msg = "服务器内部错误 !";
                    $this->errorCode = 999;
                    $this->recordErrorLog($ex);
                }
            }
            $result = [
                'errorCode' => $this->errorCode,
                'msg' => $this->msg,
                'request_url' => Request::instance()->url(),
            ];
            return json($result, $this->code);
        }
    
        /**   //自定义日志错误记录
         * @param Exception $ex
         */
        private function recordErrorLog(\Exception $ex)
        {
            Log::init([
                'type' => 'File',
                'path' => LOG_PATH,
                'level' => ['error'],
            ]);
            Log::record($ex->getMessage(), 'error');
    
        }
    
    }

## -------------------------------------------------------------------------- 
<br><?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/9/23
 * Time: 22:47
 */

namespace app\exception;

use think\Exception;

/*
 * restful API 最佳实践
 *
 * POST 创建
 * PUT 更新
 * GET 查询
 * DELETE 删除
 * 状态码:404(当前请求的页面不存在) 400(当前的参数错误) 200(查询成功!)
 * 201 202(更新成功!) 401(未授权) 403(当前的资源被禁止) 500(服务器未知错误)
 * 错误码:自定义的错误ID号
 * 统一描述错误:错误码、错误信息 、当前URL
 * 使用token令牌来授权和验证身份
 * 版本控制
 * 测试与环境分开:api.xxx.com/dev.api.xxx.com
 * url 语义要明确,最好可以望文生义,最好是有一份比较标准的文档
 */
class BaseException extends Exception
{
    public $code=500;
    public $msg ="500 内部错误 !";
    public $errorCode;

    /**
     * BaseException constructor.
     * @param array $params
     */
    public function __construct($params = [])
    {
        if (!is_array($params)) {
            return false;
        } else {
            if (array_key_exists('code', $params)) {
                $this->code = $params['code'];
            }
            if (array_key_exists('msg', $params)) {
                $this->msg = $params['msg'];
            } 
            if (array_key_exists('errorCode', $params)) {
                $this->errorCode = $params['errorCode'];
            }
        }
    }
}
## -------------------------------------------------------------------------
### 用法
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/9/24
 * Time: 12:19
 */

namespace app\exception;

class ParameterException extends  BaseException
{
 public $code = '400';
 public $msg= "内部错误";
 public $errorCode = '10000';
}
### --------------------------------------------------------------------------------------------
###### 测试
<br><?php
namespace app\admin\controller;

use app\admin\validate\TestValidate;
use app\exception\TestException;
use think\Exception;

class Index
{
    public function index( )
    {
      
        if ( true){
           throw  newParameterException();
      	}
        return json(['code'=>200],'200');
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值