国产+高潮+在线,国产 av 仑乱内谢,www国产亚洲精品久久,51国产偷自视频区视频,成人午夜精品网站在线观看

自定義404

如果你想動態(tài)控制404的內(nèi)容時,例如在ajax請求時返回json數(shù)據(jù) {"code:"404", "msg":"404 not found"},頁面請求時返回app/view/404.html模版,請參考如下示例

以下以php原生模版為例,其它模版twig blade think-tmplate 原理類似

創(chuàng)建文件app/view/404.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>404 not found</title>
</head>
<body>
<?=htmlspecialchars($error)?>
</body>
</html>

config/route.php中加入如下代碼:

use support\Request;
use Webman\Route;

Route::fallback(function(Request $request){
    // ajax請求時返回json
    if ($request->expectsJson()) {
        return json(['code' => 404, 'msg' => '404 not found']);
    }
    // 頁面請求返回404.html模版
    return view('404', ['error' => 'some error'])->withStatus(404);
});

自定義405

從webman-framework 1.5.23開始,回調(diào)函數(shù)支持傳遞status參數(shù),如果status是404則代表請求不存在,405代表不支持當前請求方法(例如Route::post()設(shè)置的路由通過GET方式訪問)

use support\Request;
use Webman\Route;

Route::fallback(function(Request $request, $status) {
    $map = [
        404 => '404 not found',
        405 => '405 method not allowed',
    ];
    return response($map[$status], $status);
});

自定義500

新建app/view/500.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>500 Internal Server Error</title>
</head>
<body>
自定義錯誤模版:
<?=htmlspecialchars($exception)?>
</body>
</html>

新建app/exception/Handler.php(如目錄不存在請自行創(chuàng)建)

<?php

namespace app\exception;

use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;

class Handler extends \support\exception\Handler
{
    /**
     * 渲染返回
     * @param Request $request
     * @param Throwable $exception
     * @return Response
     */
    public function render(Request $request, Throwable $exception) : Response
    {
        $code = $exception->getCode();
        // ajax請求返回json數(shù)據(jù)
        if ($request->expectsJson()) {
            return json(['code' => $code ? $code : 500, 'msg' => $exception->getMessage()]);
        }
        // 頁面請求返回500.html模版
        return view('500', ['exception' => $exception], '')->withStatus(500);
    }
}

配置config/exception.php

return [
    '' => \app\exception\Handler::class,
];
編輯于2025-04-18 17:20:05 完善本頁 +發(fā)起討論
贊助商