Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Distinguish between HTTP 404 and 405 #51

Open
jonaskohl opened this issue Jul 16, 2023 · 0 comments
Open

Distinguish between HTTP 404 and 405 #51

jonaskohl opened this issue Jul 16, 2023 · 0 comments
Assignees

Comments

@jonaskohl
Copy link

jonaskohl commented Jul 16, 2023

Currently the router throws a RouteNotFoundException either if it doesn't find a route with a matching pattern or a matching method. My suggestion is to introduce either a property on RouteNotFoundException or a new MethodMismatchException to differentiate between a 404 Not Found and a 405 Method Not Allowed error.

Example:

<?php

use MiladRahimi\PhpRouter\Router;
use Laminas\Diactoros\Response\HtmlResponse;
use MiladRahimi\PhpRouter\Exceptions\RouteNotFoundException;

require __DIR__ . "/vendor/autoload.php";

$router = Router::create();
$router->get('/', function() use ($twig) {
    return new HtmlResponse("<h1>Test</h1>\n");
});

try {
	$router->dispatch();
} catch (RouteNotFoundException $ex) {
	// We have no way to tell if it really is a 404 or 405 error...
	$router->getPublisher()->publish(new HtmlResponse('Not found.', 404));
} catch (\Throwable $e) {
    $router->getPublisher()->publish(new HtmlResponse('Internal error.', 500));
}

If we POST http://<DOMAIN>/ we get a HTTP/1.1 404 Not Found, despite it actually resembeling a 405 error.

Proposal:

<?php

use MiladRahimi\PhpRouter\Router;
use Laminas\Diactoros\Response\HtmlResponse;
use MiladRahimi\PhpRouter\Exceptions\RouteNotFoundException;
use MiladRahimi\PhpRouter\Exceptions\MethodMismatchException;

require __DIR__ . "/vendor/autoload.php";

$router = Router::create();
$router->get('/', function() use ($twig) {
    return new HtmlResponse("<h1>Test</h1>\n");
});

try {
	$router->dispatch();
} catch (RouteNotFoundException $ex) {
	$router->getPublisher()->publish(new HtmlResponse('Not found.', 404));
} catch (MethodMismatchException $ex) {
	$router->getPublisher()->publish(new HtmlResponse('Cannot ' . htmlentities($_SERVER["REQUEST_METHOD"]) . " " . htmlentities($_SERVER["REQUEST_URI"]), 405));
} catch (\Throwable $e) {
    $router->getPublisher()->publish(new HtmlResponse('Internal error.', 500));
}

If we now POST http://<DOMAIN>/ we correctly get a HTTP/1.1 405 Method Not Allowed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants