<?php


namespace App\Exception;


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

use Api\PhpUtils\Log\FileLog;
use Helpers\ApiResponse;
use Yaf\Registry;

class ExceptionHandler
{
    use ApiResponse;

    private $msg;
    private $code;

    public function render(\Throwable $e)
    {
        if ($e instanceof BaseException)
        {
            // 自定义异常
            $this->code = $e->code;
            $this->msg = $e->msg;
        }
        else{
            // 服务器未处理异常
            if(_IS_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  = appConfig('exception.sys.msg');
            $this->code = appConfig('exception.sys.code');
            $this->recordErrorLog($e);
        }

        if(PHP_SAPI != 'cli') {
            $this->failed($this->code, $this->msg);
        }
    }

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

            $msg = ' file_name : '.$file_name . ' line_num : '.$line_num . ' message : ' . $message;
            FileLog::error(get_class($e) . ' handler', $msg, $e, 'wanjilong@yidian-inc.com');
            //FileLog::error(get_class($e) . ' handler', $msg, $e);

        }elseif( is_string($e) || is_int($e)){
            FileLog::error('exception handler', $e);
        }
    }
}