Triggering Errors With PHP

Developers can trigger custom PHP error messages using the trigger_error function; but throwing an exception is often better.

552 views
d

By. Jacob

Edited: 2020-09-24 17:08

Traditional PHP errors can be triggered using the trigger_error function, but this practice is outdated for most purposes. Instead we should now throw an exception which is more flexible.

There may still be situations where it makes sense to use trigger_error instead of exception throwing, but if you are in doubt which one to use, you should probably throw an exception.

Errors that are sent using trigger_error can also be handled by a custom error handler.

To trigger an error we may do like this:

trigger_error("A dependency was not included.", E_USER_ERROR);

User error types

Errors sent with trigger_error is prefixed with E_USER and includes the following:

  1. E_USER_ERROR
  2. E_USER_WARNING
  3. E_USER_NOTICE
  4. E_USER_DEPRECATED

When should you trigger errors?

When using procedural code it makes more sense to use traditional PHP errors, but it is also possible to throw exceptions within functions.

If a function or method is deprecated, then you can also use trigger_error to trigger a E_USER_DEPRECATED message; this would indicate to a user that a feature is deprecated and going to be removed in a future update.

trigger_error("This feature will be removed soon.", E_USER_DEPRECATED);

It is recommended to disable error messages in production environments, as this makes sure they are only shown to the developer.

Tell us what you think:

  1. How to create a custom error handler for PHP that handles non-fetal errors.
  2. The fread function can be dangerous when used inside a loop in PHP, find out how to secure it in this article.
  3. How to show or hide error messages in PHP. There are several ways to do this; from within the PHP scripts themselves, from php.ini, or from changing Apache configuration files.
  4. E_STRICT will only show you warnings about deprecated PHP features and things that might not be future-proof, it will not show you notices or warnings; E_ALL includes everything, and that includes E_STRICT messages.

More in: PHP Errors