CodeIgniter Forums
set404Override - JSON not working - 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: set404Override - JSON not working (/showthread.php?tid=81309)



set404Override - JSON not working - azmanishak - 02-15-2022

I'm creating a RESTFUl API with JWT. The allowed method is POST, which I've setup in Routes.php. So when end use request with other than "POST" method will end up as 404. I have tried to changed in Routes.php as follows:

PHP Code:
$routes->set404Override('App\Controllers\ErrorController::index'); 
and this is my Controller:

Code:
<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;

class ErrorController extends BaseController
{
    public function index()
    {
        return Services::response()
            ->setJSON([
                'status_code' => ResponseInterface::HTTP_NOT_FOUND,
                'status_message' => 'Unknown method'
            ]);
    }
}

But I test in POSTMAN, it return empty or blank. How can I return JSON in custom 404?


RE: set404Override - JSON not working - iRedds - 02-15-2022

I think it's a bug.
Until the bug is fixed, you can use this solution.

PHP Code:
public function index()
{
    
Services::response()->setHeader('Content-Type''application/json');

    echo 
json_encode([
        
'status_code' => ResponseInterface::HTTP_NOT_FOUND,
        
'status_message' => 'Unknown method'
    
]);


https://github.com/codeigniter4/CodeIgniter4/issues/5697


RE: set404Override - JSON not working - azmanishak - 02-15-2022

Thanks @iRedds will give it a try.