欢迎光临
我们一直在努力

使用 WP_Error 类进行 WordPress 错误处理(一)

建站超值云服务器,限时71元/月

本文目录
[隐藏]

  • 1Understanding WP_Error
  • 2How the WP_Error Class Works
  • 3Summary

本文是《使用 WP_Error 类进行 WordPress 错误处理》系列教程的第 1 部分,该系列共包含以下 2 个部分:

  1. 使用 WP_Error 类进行 WordPress 错误处理(一)
  2. 使用 WP_Error 类进行 WordPress 错误处理(二)

由于用户的行为是无法预测的,一个网站或应用程序可被编程为正确地拒绝由用户输入的任何无效数据,并通知用户该数据是无效的。这个过程被称为错误处理。

WordPress 附带了一个 WP_Error 类,让 WordPress 本身和它的插件可以更容易地进行错误处理。本系列将详细讲解如何使用 WP_Error 类进行 WordPress 错误处理,让 WordPress 开发新手掌握这一技能。

注:由于时间精力有限,本教程没办法翻译分享,希望朋友们可以加入我们,帮助我们进行翻译,有小酬谢,有意者请联系倡萌QQ 745722006(注明:教程翻译)。

以下为原文:http://code.tutsplus.com/tutorials/wordpress-error-handling-with-wp_error-class-i–cms-21120

Even if you wear an S on your chest, when it comes to programming, errors will undoubtedly creep into your application. These errors are either caused by we the programmers as a result of code error or by the users who are unwilling to conform to the application or website constraints.

The errors caused by the end users are usually more adverse than that of the programmer reason because the data or information entered by the user is unpredictable.

For example, in an email form field, instead of entering a valid email, the user might enter a non-email text. If the website lack a solid error handling mechanism, the user can gain unauthorized access to sensitive information.

Since users behavior can’t be predicted, a website or application can be programmed to out-rightly reject any invalid data entered by the user and inform the user that the data was invalid. This process is what is termed error handling

WordPress ships with a WP_Error  class that makes error handling within plugins and WordPress itself much easier.

Understanding WP_Error

The WP_Error class consist of two properties and eight methods. These properties are used internally by the class and you likely won’t be needing these properties as most of the task you want to carry out can be accomplished using the class methods.

Below are the two class properties and what they do.

  • $errors is an array containing the list of errors.
  • $error_data is an array containing the list of data for error codes.

Before we examine the class methods, I will like to explain these three terms use internally by the WP_Errorclass –  Code, Message, Data.

Do not worry if they’re difficult to understand right now – things we become clearer as we examine code samples in succeeding section.

  • Code is similar to a key/value pair data such as an array: the code in this sense is the key.
  • The Message is the value of a key/value pair saved to the errors class property.
  • Data, like the message above, it is the value of a key ( code ) but saved to the error_data property.

Now to the class methods and what they do:

  • __construct() is a PHP magic method accept three arguments – code, message and data. Passing the argument on instantiation of the WP_Error class sets up the error message.
  • get_error_codes() returns an array list of all error codes if available.
  • get_error_code() retrieves the first error code and returns string, integer or empty if there is no error codes.
  • get_error_messages( $code ) retrieve all error messages when the code argument is absent or error messages matching the code argument. Returns an array of error strings on success, or empty array on failure (if using code parameter).
  • get_error_message( $code ) gets single error message. This will get the first message available for the code. If no code is given then the first code available will be used. Returns an error string. 
  • get_error_data( $code ) retrieve error data for a given error code. Returns the data or null, if no errors. 
  • add( $code, $message, $data ) append more error messages to list of error messages.
  • add_data( $data, $code ) adds data for error code. The error code can only contain one piece of error data.

How the WP_Error Class Works

To use the WP_Error class for error handling, firstly instantiate the class follow by the use of the class method. You can add an error message passing the code, message, and data on instantiation.

1
$my_error = new WP_Error( 'toy', 'my favorite toy is dolly' );

$my_error = new WP_Error( ‘toy’, ‘my favorite toy is dolly’ );

Examining the structure of the $my_error object via print_r() reveals:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
WP_Error Object
(
    [errors] => Array
        (
            [toy] => Array
                (
                    [0] => my favorite toy is dolly
                )
 
        )
 
    [error_data] => Array
        (
        )

WP_Error Object ( [errors] => Array ( [toy] => Array ( [0] => my favorite toy is dolly ) ) [error_data] => Array ( )

Notice that our defined error is stored in errors class property while the error_data property has no data.

Passing a third argument on instantiation create a data with the code (first argument) being the array key and the third argument (data), the array value.

1
2
3
<?php
$my_error = new WP_Error( 'toy', 'my favorite toy is dolly', 'my best' );
print_r( $my_error );

<?php $my_error = new WP_Error( ‘toy’, ‘my favorite toy is dolly’, ‘my best’ ); print_r( $my_error );

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
WP_Error Object
(
    [errors] => Array
        (
            [toy] => Array
                (
                    [0] => my favorite toy is dolly
                )
 
        )
 
    [error_data] => Array
        (
            [toy] => my best
        )
 
)

WP_Error Object ( [errors] => Array ( [toy] => Array ( [0] => my favorite toy is dolly ) ) [error_data] => Array ( [toy] => my best ) )

To add or append more error messages to the list of errors, the add method is used which accept code,message, and data as method argument.

1
2
3
<?php
$my_error = new WP_Error( 'toy', 'my favorite toy is dolly', 'best toy' );
$my_error->add( 'game', 'my favorite game console is PS4' );

<?php $my_error = new WP_Error( ‘toy’, ‘my favorite toy is dolly’, ‘best toy’ ); $my_error->add( ‘game’, ‘my favorite game console is PS4’ );

Passing a third argument (mixed data-type) to the add() method adds a data to the error code.

1
2
<?php
$my_error->add( 'game', 'my favorite game console is PS4', 'best game' );

<?php $my_error->add( ‘game’, ‘my favorite game console is PS4’, ‘best game’ );

Using print_r()  again, let’s view the structure and information of our $my_error WP_Error object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
WP_Error Object
(
    [errors] => Array
        (
            [toy] => Array
                (
                    [0] => my favorite toy is dolly
                )
 
            [game] => Array
                (
                    [0] => my favorite game console is PS4
                )
 
        )
 
    [error_data] => Array
        (
            [toy] => best toy
            [game] => best game
        )
 
)

WP_Error Object ( [errors] => Array ( [toy] => Array ( [0] => my favorite toy is dolly ) [game] => Array ( [0] => my favorite game console is PS4 ) ) [error_data] => Array ( [toy] => best toy [game] => best game ) )

The add_data() method could also be use to add strictly data for error code. The error code can only contain one error data.

1
$my_error->add_data( 'my best teacher is Uncle Sam', 'teacher' );

$my_error->add_data( ‘my best teacher is Uncle Sam’, ‘teacher’ );

We have learned how to instantiate and add error message and data to the WP_Error object. Let’s see how to retrieve the error message, code and data.

Using the get_error_codes() method returns an array list of all error codes.

1
2
3
4
5
6
7
8
print_r( $my_error->get_error_codes() );
/* returns
 Array
 (
 [0] => toy
 [1] => game
 )
 */

print_r( $my_error->get_error_codes() ); /* returns Array ( [0] => toy [1] => game ) */

While get_error_code() returns only the first error code.

1
print_r( $my_error->get_error_code() ); // toy

print_r( $my_error->get_error_code() ); // toy

The get_error_messages() Retrieve all error messages when the code argument is absent or error messages matching the code argument.

1
2
3
4
5
6
7
8
print_r( $my_error->get_error_messages() );
/* returns
 Array
 (
 [0] => my favorite toy is dolly
 [1] => my favorite game console is PS4
 )
 */

print_r( $my_error->get_error_messages() ); /* returns Array ( [0] => my favorite toy is dolly [1] => my favorite game console is PS4 ) */

 

1
2
3
4
5
6
7
8
9
print_r( $my_error->get_error_messages( 'game' ) );
/* returns
 
 Array
(
    [0] => my favorite game console is PS4
)
 
*/

print_r( $my_error->get_error_messages( ‘game’ ) ); /* returns Array ( [0] => my favorite game console is PS4 ) */

The get_error_message() returns a single error message matching the code. if no code, returns the first error message.

1
2
print_r( $my_error->get_error_message() );
// my favorite toy is dolly

print_r( $my_error->get_error_message() ); // my favorite toy is dolly

The get_error_data() returns the data for error code.

1
2
print_r( $my_error->get_error_data() );
// best toy

print_r( $my_error->get_error_data() ); // best toy

 

1
2
print_r( $my_error->get_error_data( 'teacher' ) );
// my best teacher is Uncle Sam

print_r( $my_error->get_error_data( ‘teacher’ ) ); // my best teacher is Uncle Sam

When building a plugin, you might want to check if a variable is a WP_Error object. This is where is_wp_error() comes in handy.

Also, you might also want to make sure a WP_Error object doesn’t contains any error message before an action is processed. For example, the code snippet below check if $my_error object doesn’t contain any error. If true, “No error, we’re good to go” is echoed.

1
2
3
if ( 1 > count( $my_error->get_error_messages() ) ) {
    echo "No error, we're good to go";
}

if ( 1 > count( $my_error->get_error_messages() ) ) { echo “No error, we’re good to go”; }

Summary

In this first part of the series about handling errors in WordPress using WP_Error, we took a look at the class to us, explained what each class method does with code examples.

阅读该系列的其他文章: 下一篇:使用 WP_Error 类进行 WordPress 错误处理(二)

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 使用 WP_Error 类进行 WordPress 错误处理(一)
分享到: 更多 (0)