ExceptionHandle.php 2.0 KB
<?php

namespace app\api\library;

use app\api\library\Exception\BaseException;
use Exception;
use think\exception\Handle;

/**
 * 自定义API模块的错误显示
 */
class ExceptionHandle extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    public function render(Exception $e)
    {
        // 在生产环境下返回code信息
        if($e instanceof BaseException){
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errCode;
        }elseif($e instanceof \think\exception\ValidateException){
            $this->code = -2;
            $this->errorCode = 200;
            $this->msg = $e->getError();
        }
        else{
            if(config('app_debug')){
                return parent::render($e);
            }else{
                $this->code = 500;
                $this->msg ='服务器内部异常';
                $this->errorCode = 500;
            }

        }
        return writeJson([],$this->code,$this->msg,$this->errorCode);
//        $url = $_SERVER['SERVER_NAME'];
//        switch ($url){
//            case config("environment.local_url"):
//                $this->code = $this->errorCode = 500;
//                $this->msg = 'An error occurred';
//                // 验证异常
//                if ($e instanceof \think\exception\ValidateException) {
//                    $this->code = -2;
//                    $this->errorCode = 200;
//                    $this->msg = $e->getError();
//                }
//                // Http异常
//                else if($e instanceof BaseException){
//                    $this->code = $e->code;
//                    $this->msg = $e->msg;
//                    $this->errorCode = $e->errCode;
//                }
//                return json(['code' => $this->code, 'msg' => $this->msg, 'time' => time(), 'data' => null], $this->errorCode);
//        }
        //其它此交由系统处理
//        return parent::render($e);
    }

}