<?php


namespace App\Exception;


/*
 * 重写Handle的render方法，实现自定义异常消息
 */

use Helpers\ApiResponse;
use Yaf\Registry;

class ExceptionHandler
{
    use ApiResponse;

    private $msg;
    private $code;

    public function render(\Throwable $e)
    {
        $debug = Registry::get('config')->debug;

        if ($e instanceof BaseException)
        {
            // 自定义异常
            $this->code = $e->code;
            $this->msg = $e->msg;
        }
        else{
            // 服务器未处理异常
            if($debug){
                $message = $e->getMessage();
                $file_name = $e->getFile();
                $line_num = $e->getLine();
                echo ' file_name : '.$file_name . '<br> line_num : '.$line_num . '<br> message : ' . $message;
                exit;
            }

            $this->msg  = Registry::get('config')->exception->sys->msg;
            $this->code = Registry::get('config')->exception->sys->code;
            $this->recordErrorLog($e);
        }
        $this->failed($this->code, $this->msg);
    }

    /*
     * 将异常写入日志
     */
    private function recordErrorLog($e)
    {
        if($e instanceof \ErrorException || $e instanceof \Exception){
            $message = $e->getMessage();
            $file_name = $e->getFile();
            $line_num = $e->getLine();

            $msg = ' file_name : '.$file_name . ' line_num : '.$line_num . ' message : ' . $message;
//            LogUtil::error('exception handler', $msg);
        }
        if(is_string($e) || is_int($e)){
//            LogUtil::error('exception handler', $e);
        }
    }
}