入口文件


一、入口文件

<?php

use Timo\Core\Engine;
use Timo\Exception\CoreException;

if (!isset($_SERVER['HTTP_HOST'])) {
    return false;
}

define('APP_NAME', 'api');
define('ENV', $_SERVER['HTTP_HOST'] == 'api.timophp.com' ? 'pro' : ($_SERVER['HTTP_HOST'] == 't.api.timophp.com' ? 'test' : 'dev'));
define('APP_DEBUG', ENV == 'dev');
define('ROOT_PATH', dirname(__DIR__) . DIRECTORY_SEPARATOR);

require ROOT_PATH . 'vendor/autoload.php';
require ROOT_PATH . '../TimoPHP/boot.php';

try {
    $engine = new Engine();
    $engine->start();
} catch (Exception $e) {

    CoreException::handle($e);
} catch (Error $e) {

    CoreException::handle($e);
}

二、自定义异常处理

<?php

define('APP_NAME', 'web');
define('APP_DEBUG', true);

require '../bootstrap.php';

$engine = new \Timo\Core\Engine();

// 异常处理
try {
    $engine->start();
} catch(Exception $e) {

    //跳转到404页面,异常处理和日志记录
    $engine->run('error', '_404', ['e' => $e]);
} catch(Error $e) {

    $engine->run('error', '_404', ['e' => $e]);
}

自定义异常处理,我们需要增加处理异常的控制器和方法

异常处理控制器

<?php
namespace app\web\controller;

use Timo\Core\Exception;
use Timo\Core\Log;
use Timo\Core\Response;
use Timo\Core\View;

class Error
{
    /**
     * @param $e Exception
     * @return string
     * @throws \Timo\Core\Exception
     */
    public function _404($e = null)
    {
        if (!$e instanceof \Exception && !$e instanceof \Error) {
            goto eco;
        }

        $log = [];
        $log['Message'] = $e->getMessage();
        $log['Code'] = $e->getCode();
        $log['File'] = $e->getFile();
        $log['Line'] = $e->getLine();
        $log['trace'] = explode("\n", $e->getTraceAsString());

        if (APP_DEBUG) {
            $log['trace'] = print_r($log['trace'], true);
            $log['traceArray'] = print_r($e->getTrace(), true);
            $html = '<pre>';
            foreach ($log as $key => $val) {
                $html .= $key . ':' . $val . '<br>';
            }
            return $html . '</pre>';
        }

        //记录日志
        Log::write(print_r($log, true), 'Error', 'Exception.' . date('Y-m.d'));

        eco:
        //"HTTP/1.1 404 Not Found"
        if (!isset($_GET['sendResponseCode'])) {
            Response::sendResponseCode(404);
        }
        $view = View::instance;
        $view->assign('title', '404页面 - TimoPHP');
        return $view->render();
    }
}

404模版文件

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <script src="<?= $this->res('lib/jQuery/jquery-2.2.3.min.js'); ?>"></script>
    <title><?= $this->data['title']; ?></title>
    <style>
        .box{width: 600px; margin: 100px auto 0;}
        .box p{font-family: "Century Gothic","Microsoft yahei"; font-size: 24px;}
    </style>
</head>
<body>
<div class="wrapper">
    <div class="box">
        <p>主银,服务器君找了半天,没找到您要访问的页面!</p>
    </div>
</div>
</body>

当我们访问不存在的页面时返回自定义404页面

例如:

http://www.timophp.com/8$#dfj33.php

http://www.timophp.com/YY/999/&93834##%.html