<?php
/**
 * 异常处理类
 * ============================================================================
 * Copyright 2014 大秦科技，并保留所有权利。
 * 网站地址: http://www.qintech.net；
 * ----------------------------------------------------------------------------
 * 未获商业授权之前，不得将Magic CMS用于商业用途（包括但不限于企业网站、经营性网站
 * 以营利为目的或实现盈利的网站）未经官方许可，禁止在Magic CMS的整体或任何部分基础
 * 上以发展任何派生版本、修改版本或第三方版本用于重新分发。如果您未能遵守本协议的
 * 条款，您的授权将被终止，所被许可的权利将被收回，并承担相应法律责任。
 * ============================================================================
 * Author: Shiang.Chin
 * Date:2014/12/31
**/
if (!defined('KERNEL_PATH'))exit('No direct script access allowed');
final class Error extends Exception{
    /**
     * 异常类型
     * @var string
     * @access private
     */
    private $type;

    // 是否存在多余调试信息
    private $extra;

    /**
     * 架构函数
     * @access public
     * @param string $message 异常信息
     */
    public function __construct($message, $code = 0, $extra = false){
        parent::__construct($message, $code);
        $this->type = get_class($this);
        $this->extra = $extra;
    }

    /**
     * 异常输出 所有异常处理类均通过__toString方法输出错误
     * 每次异常都会写入系统日志
     * 该方法可以被子类重载
     * @access public
     * @return array
     */
    public function __toString(){
        $trace = $this->getTrace();
        $this->class = isset($trace[0]['class']) ? $trace[0]['class'] : '';
        $this->function = isset($trace[0]['function']) ? $trace[0]['function'] : '';
        $this->file = isset($trace[0]['file']) ? $trace[0]['file'] : '';
        $this->line = isset($trace[0]['line']) ? $trace[0]['line'] : '';
        $traceInfo = '';
        $time = date('y-m-d H:i:m');
        foreach ($trace as $t) {
            if (isset($t['file'])) {
                $traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') ';
                if (isset($t['class'])) {
                    $traceInfo .= $t['class'] . $t['type'] . $t['function'];
                }
                $traceInfo .= "\n";
            }
        }
        $error['message'] = $this->message;
        $error['type'] = $this->type;
        $error['class'] = $this->class;
        $error['function'] = $this->function;
        $error['file'] = $this->file;
        $error['line'] = $this->line;
        $error['trace'] = $traceInfo;
        // 记录 Exception 日志
        if (C('LOG_RECORD')) {
            Log::Write('('.$this->type.') ' . $this->message);
        }
        return $error;
    }

}