CodeIgniter 4 Error Handling , we will see the set of exceptions and error logging that we can use in the framework codeigniter
Configuration exceptions
throw new \CodeIgniter\Exceptions\ConfigException(); : When using this exception in our application, it shows us the message CodeIgniter\Exceptions\ConfigException , use code 3
Database Exceptions
throw new \CodeIgniter\Database\Exceptions\DatabaseException(); : When using this exception in our application, it shows us the message CodeIgniter\Database\Exceptions\DatabaseException , use code 8
Exceptions with 404 status codes
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound(); : When using this exception in our application, it shows us the message 404 – File Not Found – Page Not Found
throw \CodeIgniter\Exceptions\PageNotFoundException::forEmptyController(); : When using this exception in our application, it shows us the message 404 – File Not Found – No Controller specified. an example of implementation is to use it in a system with Authorization to hide a route associated to a method
throw \CodeIgniter\Exceptions\PageNotFoundException::forControllerNotFound(); : When using this exception in our application, it shows us the message Too few arguments to function CodeIgniter\Exceptions\PageNotFoundException::forControllerNotFound(), , since it is necessary to add 2 parameters
throw \CodeIgniter\Exceptions\PageNotFoundException::forMethodNotFound(); : When using this exception in our application, it shows us the message Too few arguments to function CodeIgniter\Exceptions\PageNotFoundException::forMethodNotFound(), , since you need to add 1 parameter
Redirect exceptions
throw new \CodeIgniter\Router\Exceptions\RedirectException(); : Redirect exceptions redirect us to the base url unless we pass a route as a parameter, the status code is 302, A practical way to use this functionality is when creating a login
Log and error handling
In the environment variable file named .env , we enable error logging on codeigniter 4, removing the hash # sign
#--------------------------------------------------------------------
# LOGGER
#--------------------------------------------------------------------
logger.threshold = 4
Now let’s make some syntax error in our application, for example we forgot to put a semicolon at the end of this statement
return $this->response->setJSON($access)
Which would show us the error log and its cause in the file writable/logs/log-year-month-day.log
These were some ways to use CodeIgniter 4 Error Handling