For the past few weeks I’ve been working on a WordPress plugin. One of my goals was to have fancy and relevant error messages.
I contemplated writing my own error manager, and even began a very basic one. I experienced hurdle after hurdle, and finally I thought to myself, “Wouldn’t WordPress have its own error manager also?”
So I did a quick source-code search and came across the WP_Error class.
One of the hurdles I ran into in creating my own error manager was error localization. The WP_Error class makes localizing error messages extremely simple.
Adding Error Messages
To add an error message, the first thing you’ll want to do is instantiate your own instance of WP_Error.
$myErrors = new WP_Error();
The next step is to add in your error messages.
$myErrors->add('access_denied', __('You do not have permission to do that.',$myLocalizationName));
There are a few things to notice here. There is something called an error code, which you will use to look up the full error message. You also have the full error message, which uses the __ function for localization.
Retrieving Error Messages
After you have added in your error messages, you’ll want to retrieve them at some point.
Retrieving an error message is as simple as calling the get_error_message method and passing it your error code.
$errorMessage = $myErrors->get_error_message($code);
From there you can echo out your message in whatever manner suits you.
Applications
Using the WP_Error class is ideal for those with themes and plugins.
For plugins, it’s best to have your errors as a member of a class. Using the class approach assures that you can access the errors throughout your methods, and also avoid naming conflicts.
For themes, you can also create your own class, or have a prefixed variable so you don’t have possible conflicts with other variables.
Downloadable and Example Code
Here is some downloadable code with an example of how the class might be used in a theme. As stated earlier, plugin authors may want to use a class for this.
The code is assumed to be placed in a theme’s “functions.php” file.
class my_class { function my_class() { $this->localizionName = ''; $this->errors = new WP_Error(); $this->initialize_errors(); } /* get_error - Returns an error message based on the passed code Parameters - $code (the error code as a string) Returns an error message */ function get_error($code = '') { $errorMessage = $this->errors->get_error_message($code); if ($errorMessage == null) { return __("Unknown error.", $this->localizionName); } return $errorMessage; } /* Initializes all the error messages */ function initialize_errors() { $this->errors->add('my_weird_error', __('Some weird error has occurred', $myLocalizationName)); $this->errors->add('access_denied', __('You do not have permission to do that.',$myLocalizationName)); } //end function initialize_errors } $myErrors = new my_class(); echo $myErrors->get_error('my_weird_error');
The above code has two helper methods, one which retrieves the errors, and one which initializes the errors. The example is very basic, but should give you a good idea on how to use the WP_Error class.
Conclusion
There are many features of the WP_Error class not mentioned here, but you can dissect the code yourself if you like. The class is found in the wp-includes folder under classes.php.
The WP_Error class is a simple and powerful way to store errors, and output them rather easily. And the best thing, the messages can be localized.
OR:
You could just extend the WP_Error class and like, I don’t know, return a different message for get_error method. It would be half the code.
class my_class_example_error extends WP_Error {
function get_error($code='') {
return __('This is an example error.');
}
}
I mean to add
__('This is an example error.', MY_PLUGIN_LOCALIZATION);
You know Ronald, I’ll have to say that you are pretty awesome. With this information, there might be a day when working with exceptions for noobs won’t be such a huge deal.
Except the day when the noobs create everything as an exception to pass data, then I could just die.
I use a lot of plugins and I’ve even developed a few very basic plugins for myself, as a part of the learning process. I agree that error handling is very important, several times my plugins we behaving rather irratically and I had no clue as to why they were doing so.
I had created simple widgets that would simply display a predefined html code, which I could also edit in the widget edit mode. It was probably one of the most basic and simplest of widget code that could be!
But somehow for quite some time I struggled with the code since in the widgets.php page my widgets in particular were somehow creating problems. While the widgets.php page lists the widgets in a loop and it reaches my widget, it was getting truncated over there! The widgets.php would simply stop further loading and the page truncates early with a broken widgets page.
It took me quite sometime and patience of trail and error methods to find out how to correct the problem, although I still do not understand really what was causing the truncation.
This post is really helpful, I think it will help people like me who are relatively new in this area, and also it will help advanced developers to build better code! Error handling is one of the most critical parts which are often ignored by developers because they tend to feel that the errors are happening as a result of things outside of the control of their program. But it’s importance is even more in such situations. :).
Thanks for the post.
@Jacob,
Yes, extending the class would open up a nice realm of possibilities, but I wanted to keep the example simple.
I’m glad you liked the example, and I too would like to see error handling become the norm rather than the exception (no pun intended).
@Dhruva,
Thanks a lot. I hope this helps you out with error handling.
I would like to add that there is a syslogging plugin for WordPress available, which allows plugin authors to log errors and other events persistently.
@Alex
I built something like that for the core, which would allow for your plugin to hook into it and extend it further by sending errors through syslog or anything else for that matter.
However the patch is imperfect and I will have time to show it some love in a couple of weeks. It would be nice if you could find that ticket and give some input on its implementation. The more feedback, the better the next patch will be.
Great find Ronald, this will definitely help me handle errors better in the future. I would want a more better error handling though for storing run time errors which are incurred while a plugin runs, the possibilities are immense and can be easily extended with this find.