<?php
namespace app\api\exception;
use think\exception\Handle as BaseHandle;
use think\facade\Config;
use Exception;

//自定义异常处理handle类
class Handle extends BaseHandle
{
    private $code;  //状态码
    private $message;  //信息
    private $errorCode; //错误码
    //
    public function render(Exception $exception){
        //如果是自定义异常
        if($exception instanceof BaseException){
            $this->code = $exception->code;
            $this->message = $exception->message;
            $this->errorCode = $exception->errorCode;
            //如果是系统异常
        } else {
            //如果是调试模式 则显示系统错误 方便开发查看问题
            if(Config::get('app.app_debug')){
                return parent::render($exception);
            }
            //如果不是调试模式 则显示一个默认系统错误给调用者
            $this->code = 500;
            $this->message = '服务器未知错误';
            $this->errorCode = 99999;
        }

        $json = [
            'code' => $this->errorCode,
            'message' => $this->message
        ];

        return json($json,$this->code);
    }
}