app
|__web
www
|--admin
| |--index.php
|__web
|--index.php 入口文件
异常处理在入口文件
<?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]);
}
一旦在运行应用的时候发生异常和错误,都指向error控制的_404这个action
app
|--web
|--controller
|--Error.php
<?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 = Exception::buildLog($e);
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页面返回的状态码必须是404