Welcome Guest, Not a member yet? Register   Sign In
Customizable 404 Error Pages for Specific Routes
#5

(This post was last modified: 08-22-2024, 09:14 PM by datamweb.)

In my project, I solved this issue by overriding the RouteCollection class and adding a method to handle custom 404 pages for specific routes. The method I use is called setCustom404ForRoute, which works as follows:

PHP Code:
/**
 * Sets a custom 404 page for a specific route.
 *
 * This method checks if the current URI matches the specified route name
 * and if the HTTP method used is not allowed. If both conditions are met,
 * it overrides the default 404 behavior with the provided callable.
 *
 * @param callable|string|null $callable       A callable function or controller method to handle the custom 404.
 * @param string               $routeName      The name of the route to apply the custom 404 to.
 * @param array|string         $allowedMethods The allowed HTTP methods for the route.
 */
public function setCustom404ForRoute($callablestring $routeName, array|string $allowedMethods): RouteCollectionInterface
{
    /** @var RequestInterface $request */
    $request service('request');

    // Check if the current URI matches the route name and the HTTP method is not allowed
    if (uri_string() === $routeName && ! $request->is($allowedMethods)) {
        // Override the default 404 handler with the custom one
        unset($this->override404);
        $this->override404 $callable;
    }

    return $this;



To manage the responses, I've created a controller that sends error messages in a detailed JSON format. For example, if a GET method is used instead of POST on a specific route, the response looks like this:

PHP Code:
<?php

declare(strict_types=1);

/**
 * This file is part of CodeIgniter BlankCI.
 *
 * (c) Pooya Parsa Dadashi <[email protected]>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Datamweb\BlankCI\Controllers;

use 
CodeIgniter\HTTP\ResponseInterface;
use 
Datamweb\BlankCI\Controllers\Api\BaseApiController;

class 
Errors extends BaseApiController
{
    public function show404()
    {
        return $this->formatResponse(
            'error',
            ResponseInterface::HTTP_METHOD_NOT_ALLOWED,
            "The HTTP method({$this->request->getMethod()}) used is not allowed for this endpoint.",
            null,
            ['method' => 'The HTTP method used is not allowed for this endpoint. Allowed methods are: "POST".'],
            null
        
);
    }

    public function getCurrentVersion()
    {
        return '';
    }


And my Routes:

PHP Code:
$routes->post('api/v1/ticket-history/record-change''TicketHistoryController::recordChange')->setCustom404ForRoute('Datamweb\BlankCI\Controllers\Errors::Show404''api/v1/ticket-history/record-change''post'); 

Here’s an example of the response for a GET('GET', 'POST', 'DELETE','PUT' and ... ) (allowed method (POST))request when the HTTP method is not allowed:

Code:
{
    "status": "error",
    "code": 405,
    "message": "The HTTP method(GET) used is not allowed for this endpoint.",
    "data": null,
    "errors": {
        "method": "The HTTP method used is not allowed for this endpoint. Allowed methods are: \"POST\"."
    },
    "pagination": null,
    "meta": {
        "requestId": "66c80342f2dd1",
        "timestamp": "2024-08-23T03:34:26Z"
    }
}

In case the correct POST method is used but the data fails validation, the response includes a 400 error with detailed validation issues:

Code:
{
    "status": "error",
    "code": 400,
    "message": "Error in validating the data sent.",
    "data": null,
    "errors": {
        "ticket_id": "Ticket ID must be an integer.",
        "change_type": "Change type is required.",
        "old_value": "Old value is required.",
        "new_value": "New value is required.",
        "changed_by": "Changed by is required."
    },
    "pagination": null,
    "meta": {
        "requestId": "66c803780155c",
        "timestamp": "2024-08-23T03:35:20Z"
    }
}

Additionally, other routes can still use CodeIgniter's default 404 page or be overridden with a custom page using the method $routes->set404Override(). This approach allows developers to easily manage their custom 404 pages while maintaining flexibility in handling specific routes.

@kenjis This idea stems from a real need in a practical project, which is why I believe, although it requires further review for better implementation, adding it to CodeIgniter would be an excellent feature and would provide greater flexibility. and what you mentioned does not yield the same result.
Reply


Messages In This Thread
RE: Customizable 404 Error Pages for Specific Routes - by datamweb - 08-22-2024, 09:13 PM



Theme © iAndrew 2016 - Forum software by © MyBB