Tùy chỉnh 404

Nếu bạn muốn kiểm soát động nội dung của 404, chẳng hạn như trả về dữ liệu json {"code":"404", "msg":"404 not found"} trong các yêu cầu ajax, hoặc trả về mẫu app/view/404.html khi yêu cầu trang, hãy tham khảo ví dụ dưới đây.

Dưới đây là ví dụ với mẫu php thuần, các mẫu khác như twig, blade, think-template có nguyên lý tương tự.

Tạo file app/view/404.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>404 not found</title>
</head>
<body>
<?=htmlspecialchars($error)?>
</body>
</html>

Thêm mã sau vào config/route.php:

use support\Request;
use Webman\Route;

Route::fallback(function(Request $request){
    // Trả về json khi yêu cầu ajax
    if ($request->expectsJson()) {
        return json(['code' => 404, 'msg' => '404 not found']);
    }
    // Trả về mẫu 404.html khi yêu cầu trang
    return view('404', ['error' => 'some error'])->withStatus(404);
});

Tùy chỉnh 405

Từ phiên bản webman-framework 1.5.23 trở đi, hàm gọi lại hỗ trợ truyền tham số status, nếu status là 404 có nghĩa là yêu cầu không tồn tại, 405 có nghĩa là không hỗ trợ phương thức yêu cầu hiện tại (ví dụ như đường dẫn được thiết lập bằng Route::post() được truy cập bằng phương thức 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);
});

Tùy chỉnh 500

Tạo mới app/view/500.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>500 Internal Server Error</title>
</head>
<body>
Mẫu lỗi tùy chỉnh:
<?=htmlspecialchars($exception)?>
</body>
</html>

Tạo mới app/exception/Handler.php (nếu thư mục không tồn tại hãy tự tạo)

<?php

namespace app\exception;

use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;

class Handler extends \support\exception\Handler
{
    /**
     * Render và trả về
     * @param Request $request
     * @param Throwable $exception
     * @return Response
     */
    public function render(Request $request, Throwable $exception) : Response
    {
        $code = $exception->getCode();
        // Trả về dữ liệu json khi yêu cầu ajax
        if ($request->expectsJson()) {
            return json(['code' => $code ? $code : 500, 'msg' => $exception->getMessage()]);
        }
        // Trả về mẫu 500.html khi yêu cầu trang
        return view('500', ['exception' => $exception], '')->withStatus(500);
    }
}

Cấu hình config/exception.php

return [
    '' => \app\exception\Handler::class,
];