การปรับแต่ง 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){
    // ส่งคืน JSON เมื่อมีการร้องขอ AJAX
    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 เป็นต้นไป ฟังก์ชัน callback สนับสนุนการส่งผ่านพารามิเตอร์ 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();
        // ส่งคืน JSON เมื่อมีการร้องขอ AJAX
        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,
];