Custom 404
If you want to dynamically control the content of the 404 page, for example, returning JSON data {"code":"404", "msg":"404 not found"} for AJAX requests, and serving the template from app/view/404.html for page requests, please refer to the following example.
The following example uses a native PHP template, other templates such as
twig,blade, andthink-templatework similarly.
Create the file app/view/404.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>404 not found</title>
</head>
<body>
<?=htmlspecialchars($error)?>
</body>
</html>
Add the following code in config/route.php:
use support\Request;
use Webman\Route;
Route::fallback(function(Request $request){
// Return JSON for AJAX requests
if ($request->expectsJson()) {
return json(['code' => 404, 'msg' => '404 not found']);
}
// Serve the 404.html template for page requests
return view('404', ['error' => 'some error'])->withStatus(404);
});
Custom 405
Starting from webman-framework 1.5.23, the callback function supports passing a status parameter. If the status is 404, it indicates that the request does not exist, and 405 indicates that the current request method is not supported (for example, accessing a route set by Route::post() with GET method).
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);
});
Custom 500
Create app/view/500.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>500 Internal Server Error</title>
</head>
<body>
Custom error template:
<?=htmlspecialchars($exception)?>
</body>
</html>
Create app/exception/Handler.php (please create the directory if it does not exist)
<?php
namespace app\exception;
use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;
class Handler extends \support\exception\Handler
{
/**
* Render and return
* @param Request $request
* @param Throwable $exception
* @return Response
*/
public function render(Request $request, Throwable $exception) : Response
{
$code = $exception->getCode();
// Return JSON data for AJAX requests
if ($request->expectsJson()) {
return json(['code' => $code ? $code : 500, 'msg' => $exception->getMessage()]);
}
// Serve the 500.html template for page requests
return view('500', ['exception' => $exception], '')->withStatus(500);
}
}
Configure config/exception.php
return [
'' => \app\exception\Handler::class,
];