自訂404

如果你想動態控制404的內容,例如在ajax請求時返回json數據 {"code":"404", "msg":"404 not found"},網頁請求時返回app/view/404.html模版,請參考如下示例

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

創建檔案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開始,回調函數支持傳遞status參數,如果status是404則代表請求不存在,405代表不支持當前請求方法(例如Route::post()設置的路由通過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(如目錄不存在請自行創建)

<?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數據
        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,
];