Triggering Errors With PHP
Developers can trigger custom PHP error messages using the trigger_error function; but throwing an exception is often better.
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:
- E_USER_ERROR
- E_USER_WARNING
- E_USER_NOTICE
- 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: