An explanation of exception handling in thinkphp

Source: Internet
Author: User
Tags php class throw exception
and PHP default exception handling, thinkphp throw is not a simple error message, but a user-friendly error page, the following this article is mainly about the thinkphp in the exception handling of the relevant information, the text through the sample code introduced in very detailed, the need for friends can refer to the next

What is an exception

From a broader point of view, the exception contains two aspects, on the one hand is the program execution due to syntax, run-time errors, etc. caused by the exception, on the one hand is not given the correct feedback, such as the client to query a product, no query, I think this is also a kind of exception.

The first exception TP framework itself will output error messages in the page, but the second exception will not normally output any information, so it is very inconvenient to debug.

This article will detail about the thinkphp exception handling related content, share out for everyone to reference the study, the following words do not say more, come together to see the detailed introduction bar.

Prerequisite Environment

PHP now provides interfaces to the front end in many cases, so our exception handling is also based on this.

In the development phase, TP's original exception handling is to output exception information on the page, which satisfies the requirement, but in a production environment, the exception needs to be handled in other ways.

This article is all about exception handling for production environments

AOP programming

Now in many languages, is very popular AOP programming ideas, that is, the concept of cutting-oriented programming, popular, is to use a unified way to deal with problems, rather than the same way to deal with multiple problems, for exception handling, is to define unified exception information, the unified way to deal with

General idea

Custom exception handling classes, overriding the Render method of the default exception handling class, and then configuring the use of custom exception handling classes to handle all exceptions

Code implementation

Create the directory exception under the root directory, under which you create the Exceptionhandle.php class to inherit the handle class

Class Exceptionhandler extends Handle

Create several properties that define the exception information

HTTP error code private $code; Custom exception information private $msg; Custom error code private $errorCode;

Overriding the Render method in the Handle class, when we throw exception information in code using the throw new Exception (), we actually call the Render method, so we're going to override this method to return our own information

Public function render (Exception $ex)  {  return json ([' msg ' = ' + ' Custom exception information ']); nbsp;}

Create a new controller Product below, add a method, test

Public Function GetProduct ($id)  {  try{   3/0;  }  catch (Exception $ex) {   throw $ex;  }  }

Then add the following route

Route::get ("Product/:id", "Api/v1". Product/getproduct ");

Enter the following URL test

Http://z.cn/product/2

The page output results are as follows

Visible, it does not perform a custom exception-handling function.

Using custom exception Handling

Modify the following configuration in config.php

Exception handling Handle class leave blank using \think\exception\handle  ' exception_handle ' = ' app\lib\exception\exceptionhandler ',

And then run

Custom Exception Handling Classes

A class of exceptions is an exception caused by a user's behavior, such as no query to the qualifying data (from another perspective, this is not an exception), and a class of errors are run-time errors. User-induced exceptions can be categorized into a variety of types, so you need to customize the related classes.

First define a parent class

Class Baseexception extends Exception {  //http Status code public  $code;//Error specific message public  $msg;//Custom error code public  $ ErrorCode;   The constructor is used to receive incoming exception information and initialize the properties in the class public  function __construct ($params)  {   if (!is_array ($params))    { return;   }   if (array_key_exists (' Code ', $params)) {    $this->code = $params [' Code '];   }   if (array_key_exists (' msg ', $params)) {    $this->msg = $params [' msg '];   }   if (array_key_exists (' ErrorCode ', $params)) {    $this->errorcode = $params [' ErrorCode '];}}  }

Then define an exception handling class that handles missing product information to override individual attributes in the parent class, and the property information in this class may be modified, such as MSG

Class ProductNotFoundException extends Baseexception {  //http Status code public  $code = 404;//Error specific message public  $msg = " The requested product does not exist "; Custom error code public  $errorCode = 40000;}

Handling different exceptions

In the Render method, the difference is handled according to the exception

Two types of non-type exceptions are handled: 1, user error 2. Code with Run   -time error if ($ex instanceof baseexception) {    } else {     }

Description: When throwing an exception, the render function is executed, and the thrown exception object is copied to the parameter $ex, so the exception type can be judged based on this parameter

Now the key is the production environment, so you want to return the exception information, the front-end people can understand, rather than the same as above to output error messages in the page, including stack information and so on.

So before the front end of the staff can understand the information must be JSON (of course, it can be XML), modify the Render method

if ($ex instanceof baseexception) {    $this->code = $ex->code;    $this->msg = $ex->msg;    $this->errorcode = $ex->errorcode;   } else {//Here are various exceptions generated at run time, so the exception information cannot be accurately output, so only the unified output is the server error message    $this->code =.    $this->msg = "Server internal error";    $this->errorcode = 999;   }

Then return the error message in JSON format

$result = [    ' msg ' = + $this->msg,    ' error_code ' = ' $this->errorcode,    ' request_url ' = Request ()->url ()   ];   Return JSON ($result, $this->code);

At this point, the global exception handling is written, and the following code is tested in product.php

Public Function GetProduct ($id)  {   //handler run-time error   /*try{    3/0;   }   catch (Exception $ex) {    throw $ex;   } *   //Handling errors generated by user behavior   $error =[    ' msg ' = ' did not find the right product '   ];   $ex =new productnotfoundexception ($error);   throw $ex;  }

Hint: production environment do not forget to change App_debug to False

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.