कस्टम 404

यदि आप 404 सामग्री को गतिशील रूप से नियंत्रित करना चाहते हैं, जैसे कि ajax अनुरोध पर json डेटा लौटाना {"code":"404", "msg":"404 not found"} और पृष्ठ अनुरोध पर app/view/404.html टेम्पलेट लौटाना, तो कृपया निम्नलिखित उदाहरण देखें।

नीचे php मूल टेम्पलेट का उदाहरण दिया गया है, अन्य टेम्पलेट twig blade think-tmplate का सिद्धांत समान है।

फाइल बनाएँ 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 से शुरू होकर, कॉलबैक फ़ंक्शन स्थिति पैरामीटर को पारित करने का समर्थन करता है, यदि स्थिति 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,
];