Personalizzazione del 404
Se desideri controllare dinamicamente il contenuto del 404, ad esempio restituendo dati json {"code":"404", "msg":"404 not found"}
durante le richieste ajax, e restituendo il modello app/view/404.html
per le richieste delle pagine, fai riferimento al seguente esempio.
Di seguito si utilizza un modello php nativo, i principi sono simili per altri modelli come
twig
,blade
,think-template
.
Crea il file app/view/404.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>404 not found</title>
</head>
<body>
<?=htmlspecialchars($error)?>
</body>
</html>
Aggiungi il seguente codice in config/route.php
:
use support\Request;
use Webman\Route;
Route::fallback(function(Request $request){
// restituisci json per richieste ajax
if ($request->expectsJson()) {
return json(['code' => 404, 'msg' => '404 not found']);
}
// restituisci il modello 404.html per le richieste delle pagine
return view('404', ['error' => 'some error'])->withStatus(404);
});
Personalizzazione del 405
A partire da webman-framework 1.5.23, la funzione di callback supporta il passaggio del parametro status. Se lo status è 404 indica che la richiesta non esiste, mentre 405 indica che il metodo di richiesta attuale non è supportato (ad esempio, una rotta impostata con Route::post() viene accessibile tramite metodo 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);
});
Personalizzazione del 500
Crea app/view/500.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>500 Internal Server Error</title>
</head>
<body>
Modello di errore personalizzato:
<?=htmlspecialchars($exception)?>
</body>
</html>
Crea app/exception/Handler.php
(se la directory non esiste, creala tu stesso)
<?php
namespace app\exception;
use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;
class Handler extends \support\exception\Handler
{
/**
* Renderizza e restituisce
* @param Request $request
* @param Throwable $exception
* @return Response
*/
public function render(Request $request, Throwable $exception) : Response
{
$code = $exception->getCode();
// restituisci dati json per richieste ajax
if ($request->expectsJson()) {
return json(['code' => $code ? $code : 500, 'msg' => $exception->getMessage()]);
}
// restituisci il modello 500.html per le richieste delle pagine
return view('500', ['exception' => $exception], '')->withStatus(500);
}
}
Configura config/exception.php
return [
'' => \app\exception\Handler::class,
];