Özelleştirilmiş 404
Eğer 404 içeriğini dinamik olarak kontrol etmek istiyorsanız, örneğin ajax isteği sırasında json verisi {"code":"404", "msg":"404 not found"}
döndürmek, sayfa isteği sırasında app/view/404.html
şablonunu geri döndürmek için aşağıdaki örneğe bakabilirsiniz.
Aşağıdaki örnek, php saf şablonu kullanılarak verilmiştir; diğer şablonlar
twig
,blade
,think-tmplate
benzer prensiplerle çalışır.
app/view/404.html
dosyasını oluşturun:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>404 not found</title>
</head>
<body>
<?=htmlspecialchars($error)?>
</body>
</html>
config/route.php
dosyasına aşağıdaki kodu ekleyin:
use support\Request;
use Webman\Route;
Route::fallback(function(Request $request){
// ajax isteği durumunda json döndür
if ($request->expectsJson()) {
return json(['code' => 404, 'msg' => '404 not found']);
}
// sayfa isteği için 404.html şablonunu döndür
return view('404', ['error' => 'some error'])->withStatus(404);
});
Özelleştirilmiş 405
webman-framework 1.5.23 itibarıyla, geri çağırma fonksiyonları status parametresini almayı destekler; eğer status 404 ise, bu istek yok demektir, 405 ise mevcut istek yöntemini desteklememektedir (örneğin Route::post() ile ayarlanmış bir yolu GET yöntemiyle erişmek).
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);
});
Özelleştirilmiş 500
app/view/500.html
dosyasını oluşturun:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>500 Internal Server Error</title>
</head>
<body>
Özelleştirilmiş hata şablonu:
<?=htmlspecialchars($exception)?>
</body>
</html>
app/exception/Handler.php
dosyasını oluşturun (katalog mevcut değilse kendiniz oluşturun):
<?php
namespace app\exception;
use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;
class Handler extends \support\exception\Handler
{
/**
* Render edilecek dönüş
* @param Request $request
* @param Throwable $exception
* @return Response
*/
public function render(Request $request, Throwable $exception) : Response
{
$code = $exception->getCode();
// ajax isteği durumunda json verisi döndür
if ($request->expectsJson()) {
return json(['code' => $code ? $code : 500, 'msg' => $exception->getMessage()]);
}
// sayfa isteği için 500.html şablonunu döndür
return view('500', ['exception' => $exception], '')->withStatus(500);
}
}
config/exception.php
dosyasını yapılandırın:
return [
'' => \app\exception\Handler::class,
];