Search code examples
phpcodeigniter-4

Codeigniter - How to show custom error code


My problem is sounds quiet trivial but yet I've found no solution, not even here. I want to show custom error with custom code on Codeigniter4. So I did this

show_error('there is an error !', '600');

But I get this

Call to undefined function App\Controllers\show_error()

I assumed that I can directly use it like shown in the documentation (Please Codeigniter team, write the docs properly) as it says nothing about which use need to be included.


Solution

  • In Codeigniter 4, show_error function is not available as a global function like in previous version. You should make a custom class for handling custom errors.

    Something like:

    namespace App\Exceptions;
    
    use CodeIgniter\Exceptions\Exception;
    
    class CustomException extends Exception
    {
        protected $code = 600;
        protected $message = 'There is an error!';
    }
    
    

    Then use throw new \App\Exceptions\CustomException(); wherever you wanted to trigger this custom error.