사용자 정의 404
만약 AJAX 요청 시 {"code":"404", "msg":"404 not found"}
JSON 데이터를 반환하거나, 페이지 요청 시 app/view/404.html
템플릿을 반환하여 404 내용을 동적으로 제어하고 싶다면, 아래 예제를 참조하세요.
아래는 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,
];