CodeIgniter Forums
Setting 404 Status Code - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Setting 404 Status Code (/showthread.php?tid=87931)



Setting 404 Status Code - SoccerGuy3 - 06-22-2023

Recently discovered that my 404 override was throwing errors silently into the logs in production. Trying to troubleshoot it this morning. 

This is my code in the app/Config/Routes.php file:

PHP Code:
$routes->set404Override(static function() {
   $response->setStatusCode(404);
   echo view("error_404.php");
 }); 

This produces an error message in the log (in production) (Line 23 being the $response->setStatusCode(404) line):

Code:
CRITICAL - 2023-06-21 21:30:31 --> Undefined property: CodeIgniter\Router\RouteCollection::$response
in APPPATH/Config/Routes.php on line 23.
1 APPPATH/Config/Routes.php(23): CodeIgniter\Debug\Exceptions->errorHandler()
2 SYSTEMPATH/CodeIgniter.php(954): CodeIgniter\Router\RouteCollection->Config\{closure}()
3 SYSTEMPATH/CodeIgniter.php(387): CodeIgniter\CodeIgniter->display404errors()
4 FCPATH/index.php(67): CodeIgniter\CodeIgniter->run()
If I force it to try and load a bad page in development environment, it throws:

Code:
ErrorException
Undefined variable $response
APPPATH/Config/Routes.php at line 23

22    $routes->set404Override(static function() {
23        $response->setStatusCode(404);
24        echo view("error_404.php");
25    });

I thought I was following the manual, but maybe I am missing something. Any help/suggestions would be appreciated.
Marc


RE: Setting 404 Status Code - Mni.day - 06-22-2023

$this->response->
or
$response = Services::response();


RE: Setting 404 Status Code - kenjis - 06-22-2023

In the closure the $response is not initialize, and there is not $this->response.


RE: Setting 404 Status Code - Mni.day - 06-23-2023

sorry


RE: Setting 404 Status Code - Leo - 10-05-2023

THANK YOU! I finally got a correct 404 response (it used to be 200 and my SEO guy was complaining about it)
Here is the code in app\Config\Routes.php (CodeIgniter version 4.4.1):

$routes->set404Override(function () {
$response = CodeIgniter\Config\Services::response();
$response->setStatusCode(404);
return view('errors/html/error_404');
});


RE: Setting 404 Status Code - SoccerGuy3 - 10-13-2023

(10-05-2023, 12:03 AM)Leo Wrote: THANK YOU! I finally got a correct 404 response (it used to be 200 and my SEO guy was complaining about it)
Here is the code in app\Config\Routes.php (CodeIgniter version 4.4.1):

$routes->set404Override(function () {
    $response = CodeIgniter\Config\Services::response();
    $response->setStatusCode(404);
    return view('errors/html/error_404');
});

Thanks for posting this!!  Finally working correctly!