How to Use exceptions elegantly

Source: Internet
Author: User
How to Use exceptions elegantly old man said: During program development, 80% of the code is processing various exceptions.

Because php is too flexible and simple, many php users are not very familiar with exception handling. Therefore, we often see

Die ("xxx ");

Exit ("xxx ");

Such exceptions are not very friendly to the stability of the project. the main problems are as follows:

1: interrupt normal business flow roughly.

2: Debugging is very difficult.

3: poor flexibility

Let's look at these three questions:

1: Most modern frameworks have a standard processing process:

_ Before (); // A front-end controller that can initialize data.

Run (); // process the business logic

_ After (); // The rear controller. after processing the business, it has the opportunity to close the process (such as recycling resources and logging ).

However, if exit is directly used in the business logic processing (run), functions such as die will directly exit the execution of the current php script, thus skipping _ after (), this is obviously not in line with the normal logic.

2: I once experienced opening a page with a white screen. after a hard debug, I finally found a lonely exit somewhere, with no prompt, such a code is a nightmare for the debugger.

3: When the pc Internet is no longer used, the proportion of the mobile Internet has increased significantly. at this time, we often output an interface. if we directly encounter exit, the output such as die may directly cause the client to crash.

So what is the correct method of use?

Yes, it is the Exception that comes with php. the Exception that comes with php is very powerful and friendly. it may not be used by many people due to historical reasons.

Therefore, we can solve the first problem when designing the framework:

Try {

$ Ctrl-> _ before ();

$ Ctrl-> $ method ();

$ Ctrl-> _ after ();

} Catch (\ Exception $ e ){

$ Ctrl-> _ atfer (); // you can run the _ after command after an exception.

Throw $ e; // throw an exception

}

After an Exception is thrown, you can use the getTrace () method that comes with the Exception class to obtain the call stack, which facilitates debugging.

Finally, you can use set_exception_handler to customize exception handling and output the correct data format.

Post a short section of my frequently used exception handling code.

Assume our api code conventions:

{

Code: 0, // non-0 indicates an exception

Msg: "", // prompt message, with a value other than 0

Data: {} // business data when code = 0,

}

Custom exception handling class

Class MyException extends \ Exception

{

Public $ realCode = '';

Public function _ construct ($ message, $ code =-1)

{

$ This-> realCode = $ code;

Parent: :__ construct ($ message, $ code );

}

Public static function exceptionHandler (\ Exception $ exception)

{

$ Model = ZFormater: exception ($ exception); // An error occurred while formatting.

Log: info ([\ var_export ($ model, true)], 'exception'); // exception Log writing

$ Info = array ();

If (property_exists ($ exception, 'realcode ')){

$ CodeArr = explode ('_', $ exception-> realCode );

If (count ($ codeArr)> 1 ){

$ Model ['code'] = intval ($ codeArr [0]);

$ Model ['MSG '] = $ codeArr [1];

}

}

If ($ config ['debug _ mode']) {// mode, output call stack

$ Info ['debug'] = $ model;

}

$ Info ['MSG '] = $ model ['message'];

$ Info ['ret '] = empty ($ model ['code'])? -1: $ model ['code'];

If (Request: isAjax () {// ajax Request, json string output

Request: setViewMode ('json ');

}

If ('php' = Request: getViewMode () {// page Request, unified exception page display

If ($ config ['debug _ mode']) {

Request: setTplFile ('public/exception. php ');

} Else {

Request: setTplFile ('public/error. php ');

}

}

Response: display ($ info );

}

Definition of realCode:

Class ERROR

{

Const DEF_MSG = 'system exception ';

// System exception code

Const PARAM_ERROR = '1' parameter exception ';

Const NEED_LOGIN = '2 _ login required ';

Const USER_ERROR = '3 _ the user name does not exist ';

Const PASS_ERROR = '4_password exception ';

}

Then, after you use set_exception_handler ("MyException: exceptionHandler"); to handle custom exceptions, we encounter the exception logic at the business layer, the following exception can be thrown out in a unified and pleasant manner:

Throw new MyException ('param xxx error', error: PARAM_ERROR );

The final output api will be:

{

"Code": 1,

"Msg": "parameter exception"

}

In this way, you can say goodbye to exit and die.

PS: The above code is mostly taken from the zphp framework, detailed can refer to the ZPHP framework: https://github.com/shenzhe/zphp

-------------- Great split line ----------------

PHP phpfamily is established by a group of reliable people and is willing to bring some spiritual food worth tasting to PHPer!

This article is original by bucket elder brother. for details, please indicate the source information and the following QR code (long-press the identifiable QR code to follow ):

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.