Skip to content

Commit

Permalink
Merge pull request #8688 from kenjis/improve-errors.rst
Browse files Browse the repository at this point in the history
docs: Improve "Error Handling"
  • Loading branch information
kenjis authored Apr 2, 2024
2 parents 533717c + b4855dd commit d5660ce
Show file tree
Hide file tree
Showing 8 changed files with 101 additions and 44 deletions.
119 changes: 81 additions & 38 deletions user_guide_src/source/general/errors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,29 @@ Using Exceptions

This section is a quick overview for newer programmers, or for developers who are not experienced with using exceptions.

What is Exceptions
------------------

Exceptions are simply events that happen when the exception is "thrown". This halts the current flow of the script, and
execution is then sent to the error handler which displays the appropriate error page:

.. literalinclude:: errors/001.php

Catching Exceptions
-------------------

If you are calling a method that might throw an exception, you can catch that exception using a ``try/catch`` block:

.. literalinclude:: errors/002.php

If the ``$userModel`` throws an exception, it is caught and the code within the catch block is executed. In this example,
the scripts dies, echoing the error message that the ``UserModel`` defined.

Catching Specific Exceptions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In the example above, we catch any type of Exception. If we only want to watch for specific types of exceptions, like
a ``UnknownFileException``, we can specify that in the catch parameter. Any other exceptions that are thrown and are
a ``DataException``, we can specify that in the catch parameter. Any other exceptions that are thrown and are
not child classes of the caught exception will be passed on to the error handler:

.. literalinclude:: errors/003.php
Expand Down Expand Up @@ -65,7 +74,7 @@ See :ref:`setting-environment`.
Logging Exceptions
------------------

By default, all Exceptions other than 404 - Page Not Found exceptions are logged. This can be turned on and off
By default, all Exceptions other than "404 - Page Not Found" exceptions are logged. This can be turned on and off
by setting the ``$log`` value of **app/Config/Exceptions.php**:

.. literalinclude:: errors/005.php
Expand All @@ -74,8 +83,40 @@ To ignore logging on other status codes, you can set the status code to ignore i

.. literalinclude:: errors/006.php

.. note:: It is possible that logging still will not happen for exceptions if your current Log settings
are not set up to log **critical** errors, which all exceptions are logged as.
.. note:: It is possible that logging still will not happen for exceptions if your current
:ref:`Log settings <logging-configuration>`
are not set up to log ``critical`` errors, which all exceptions are logged as.

.. _logging_deprecation_warnings:

Logging Deprecation Warnings
----------------------------

.. versionadded:: 4.3.0

By default, all errors reported by ``error_reporting()`` will be thrown as an ``ErrorException`` object. These
include both ``E_DEPRECATED`` and ``E_USER_DEPRECATED`` errors. With the surge in use of PHP 8.1+, many users
may see exceptions thrown for `passing null to non-nullable arguments of internal functions <https://wiki.php.net/rfc/deprecate_null_to_scalar_internal_arg>`_.
To ease the migration to PHP 8.1, you can instruct CodeIgniter to log the deprecations instead of throwing them.

First, make sure your copy of ``Config\Exceptions`` is updated with the two new properties and set as follows:

.. literalinclude:: errors/012.php

Next, depending on the log level you set in ``Config\Exceptions::$deprecationLogLevel``, check whether the
logger threshold defined in ``Config\Logger::$threshold`` covers the deprecation log level. If not, adjust
it accordingly.

.. literalinclude:: errors/013.php

After that, subsequent deprecations will be logged instead of thrown.

This feature also works with user deprecations:

.. literalinclude:: errors/014.php

For testing your application you may want to always throw on deprecations. You may configure this by
setting the environment variable ``CODEIGNITER_SCREAM_DEPRECATIONS`` to a truthy value.

Framework Exceptions
====================
Expand All @@ -85,15 +126,17 @@ The following framework exceptions are available:
PageNotFoundException
---------------------

This is used to signal a 404, Page Not Found error. When thrown, the system will show the view found at
**app/Views/errors/html/error_404.php**. You should customize all of the error views for your site.
If, in **app/Config/Routes.php**, you have specified a 404 Override, that will be called instead of the standard
404 page:
This is used to signal a 404, Page Not Found error:

.. literalinclude:: errors/007.php

You can pass a message into the exception that will be displayed in place of the default message on the 404 page.

For the default 404 view file location, see :ref:`http-status-code-and-error-views`.

If, in **app/Config/Routing.php** or **app/Config/Routes.php**, you have specified
a :ref:`404-override`, that will be called instead of the standard 404 page.

ConfigException
---------------

Expand Down Expand Up @@ -144,52 +187,52 @@ Specify HTTP Status Code in Your Exception
.. versionadded:: 4.3.0

Since v4.3.0, you can specify the HTTP status code for your Exception class to implement
``HTTPExceptionInterface``.
``CodeIgniter\Exceptions\HTTPExceptionInterface``.

When an exception implementing ``HTTPExceptionInterface`` is caught by CodeIgniter's exception handler, the Exception code will become the HTTP status code.

.. _error-specify-exit-code:
.. _http-status-code-and-error-views:

Specify Exit Code in Your Exception
===================================
HTTP Status Code and Error Views
================================

.. versionadded:: 4.3.0
The exception handler displays the error view corresponding to the HTTP status
code, if one exists.

Since v4.3.0, you can specify the exit code for your Exception class to implement
``HasExitCodeInterface``.

When an exception implementing ``HasExitCodeInterface`` is caught by CodeIgniter's exception handler, the code returned from the ``getExitCode()`` method will become the exit code.
For example, ``PageNotFoundException`` implements the ``HTTPExceptionInterface``,
so its exception code ``404`` will be the HTTP status code. Therefore if it is
thrown, the system will show the **error_404.php** in the **app/Views/errors/html**
folder when it is a web request. If it is invoked via CLI, the system will show
the **error_404.php** in the **app/Views/errors/cli** folder.

.. _logging_deprecation_warnings:
If there is no view file corresponding to the HTTP status code, **production.php**
or **error_exception.php** will be displayed.

Logging Deprecation Warnings
============================

.. versionadded:: 4.3.0

By default, all errors reported by ``error_reporting()`` will be thrown as an ``ErrorException`` object. These
include both ``E_DEPRECATED`` and ``E_USER_DEPRECATED`` errors. With the surge in use of PHP 8.1+, many users
may see exceptions thrown for `passing null to non-nullable arguments of internal functions <https://wiki.php.net/rfc/deprecate_null_to_scalar_internal_arg>`_.
To ease the migration to PHP 8.1, you can instruct CodeIgniter to log the deprecations instead of throwing them.
.. note:: If ``display_errors`` is on in the PHP INI configuration,
**error_exception.php** is selected and a detailed error report is displayed.

First, make sure your copy of ``Config\Exceptions`` is updated with the two new properties and set as follows:
You should customize all of the error views in the **app/Views/errors/html** folder
for your site.

.. literalinclude:: errors/012.php
You can also create error views for specific HTTP status code. For example, if
you want to create an error view for "400 Bad Request", add **error_400.php**.

Next, depending on the log level you set in ``Config\Exceptions::$deprecationLogLevel``, check whether the
logger threshold defined in ``Config\Logger::$threshold`` covers the deprecation log level. If not, adjust
it accordingly.
.. warning:: If an error view file with the corresponding HTTP status code exists,
the exception handler will display that file regardless of the environment.
The view file must be implemented in such a way that it does not display
detailed error messages in production environment by yourself.

.. literalinclude:: errors/013.php
.. _error-specify-exit-code:

After that, subsequent deprecations will be logged instead of thrown.
Specify Exit Code in Your Exception
===================================

This feature also works with user deprecations:
.. versionadded:: 4.3.0

.. literalinclude:: errors/014.php
Since v4.3.0, you can specify the exit code for your Exception class to implement
``CodeIgniter\Exceptions\HasExitCodeInterface``.

For testing your application you may want to always throw on deprecations. You may configure this by
setting the environment variable ``CODEIGNITER_SCREAM_DEPRECATIONS`` to a truthy value.
When an exception implementing ``HasExitCodeInterface`` is caught by CodeIgniter's exception handler, the code returned from the ``getExitCode()`` method will become the exit code.

.. _custom-exception-handlers:

Expand Down
4 changes: 3 additions & 1 deletion user_guide_src/source/general/errors/003.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<?php

use CodeIgniter\Database\Exceptions\DataException;

try {
$user = $userModel->find($id);
} catch (\CodeIgniter\UnknownFileException $e) {
} catch (DataException $e) {
// do something here...
}
4 changes: 3 additions & 1 deletion user_guide_src/source/general/errors/004.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
<?php

use CodeIgniter\Database\Exceptions\DataException;

try {
$user = $userModel->find($id);
} catch (\CodeIgniter\UnknownFileException $e) {
} catch (DataException $e) {
// do something here...

throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
Expand Down
4 changes: 3 additions & 1 deletion user_guide_src/source/general/errors/005.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@

class Exceptions extends BaseConfig
{
public $log = true;
// ...
public bool $log = true;
// ...
}
4 changes: 3 additions & 1 deletion user_guide_src/source/general/errors/006.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@

class Exceptions extends BaseConfig
{
public $ignoredCodes = [404];
// ...
public array $ignoreCodes = [404];
// ...
}
8 changes: 6 additions & 2 deletions user_guide_src/source/general/errors/007.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
<?php

if (! $page = $pageModel->find($id)) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
use CodeIgniter\Exceptions\PageNotFoundException;

$page = $pageModel->find($id);

if ($page === null) {
throw PageNotFoundException::forPageNotFound();
}
Binary file modified user_guide_src/source/images/error.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions user_guide_src/source/incoming/routing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,8 @@ to only those defined by you, by setting the ``$autoRoute`` property to false:
.. warning:: If you use the :doc:`CSRF protection </libraries/security>`, it does not protect **GET**
requests. If the URI is accessible by the GET method, the CSRF protection will not work.

.. _404-override:

404 Override
============

Expand Down

0 comments on commit d5660ce

Please sign in to comment.