カスタム404
もし、404の内容を動的に制御したい場合、例えばajaxリクエストでjsonデータ {"code":"404", "msg":"404 not found"}
を返す場合や、ページリクエストで app/view/404.html
テンプレートを返す場合は、以下の例を参考にしてください。
以下はPHPのネイティブテンプレートの例であり、他のテンプレート
twig
blade
think-template
の原理は類似しています。
ファイル 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,
];