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 مخصص

ابتداءً من الإصدار 1.5.23 من webman-framework، يدعم دالة الاسترجاع تمرير معلمة 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,
];