Exception handling in PHP/TP5 interface design

Source: Internet
Author: User
Tags throw exception

PHP provides Exception class to handle exceptions

New Exception (' Error message (default is empty) ', ' Error code (default 0) ', ' previous exception in chain ')

You can then pass

e-GetCode () Get exception error code

Handling Exceptions

        Try {            // may throw exception code            thrownewException("Error Processing Request ", 1);             Catch (Exception$e) {            //  1. Logging            //2. Handling exceptions, the program continues/continues to throw exceptions/ Terminating program, printing exception error        }

In thinkphp, the framework comes with exception handling classes, and returns error messages as HTML pages, which are captured by the framework if the program has an error and the developer does not actively catch the exception, and then throws the HTML

When in the interface design, due to the inability to know the client type, so the form of HTML client may be unable to resolve, you need to override the exception class, in the form of JSON return error message to the client

Exception classification:

    • Custom exception: usually caused by a client passing a parameter error, this type of exception does not require logging, but it needs to return the cause of the error
    • Server Exceptions: Code errors cause exceptions, such exceptions require logging, but do not need to return the cause of the error

Server exception errors are generally thrown by PHP or the framework, custom exceptions need to be captured manually, and then thrown

Realize:

Create a new exception directory under the Application/common directory, which is the Exception class library directory

Application/common/exception/exceptionhandler (overridden exception handling Class)

<?phpnamespace app\common\Exception; Use Exception; UseThink\Exception\handle; Usethink\facade\request; UseThink\Log;classExceptionhandlerextendsHandle {Private $code; Private $msg; Private $errorCode;  Public functionRenderException $e) {        if($einstanceof Baseexception) {            //if it is a custom exception, control the HTTP status code and do not need to log//Because these are usually due to a client passing a parameter error or an exception caused by a user request//should not log            $this->code =$e-Code; $this->msg =$e-msg; $this->errorcode =$e-ErrorCode; } Else {            //If the exception is unhandled by the server, set the HTTP status code to 500 and log            if(Config (' app_debug ')) {                //you need to display the default exception page of TP in debug state, because the default page of TP//is easy to see the problem                returnParent::render ($e); }            $this->code = 500; $this->msg = ' sorry,we make a mistake. (^o^) Y; $this->errorcode = 999; $this->recorderrorlog ($e); }        $request= Request::instance (); $result= [            ' Msg ' =$this->msg, ' error_code ' =$this->errorcode, ' request_url ' =$request=$request->url (),        ]; returnJson$result,$this-code); }    /** Write exception to log*/    Private functionRecorderrorlog (Exception $e) {        Log::Init ([' Type ' = ' File ', ' path ' = = Log_path, ' level ' and ' = ' error ',        ]); Log:: Record ($e->getmessage (), ' ERROR '); }}

This class will judge the source of the anomaly and make the appropriate processing

After creating the processing class, you need to modify the corresponding configuration file so that the class becomes the framework default exception handling class

In application/config/app.php

    // exception Handling Handle class leave blank using \think\exception\handle    ' Exception_handle ' = ' \app\common\exception\exceptionhandler ',

Application/common/exception/baseexception (Custom exception class base class, base PHP comes with exception class exception)

<?phpnamespace app\common\Exception; UseThink\Exception;/** * Class Baseexception * Base class for custom exception classes*/classBaseexceptionextends Exception {     Public $code= 400;  Public $msg= ' Invalid parameters ';  Public $errorCode= 999; /** * constructor, receive an associative array * @param array $params Associative arrays should contain only code, MSG, and errorcode, and should not be null*/     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 ']; }    }}

Custom exception Classes

Application/common/exception/userexception (Custom exception, example of exception for user module)

<? phpnamespace app\common\ Exception ; class extends baseexception {    public$code = 404;      Public $msg = ' user does not exist'    ;  Public $errorCode = 60000;}

Throw a custom exception

    Try {            //todo ...            Throw New \app\common\exception\userexception ();         Catch (Exception$e) {        }

At this point, the exception display is no longer the HTML page with TP, but

{    "msg": "User does not exist",    "Error_code": 60000,    "Request_url": "/wx_shop/public/index.php/admin/banner/list "}

  

Exception handling in PHP/TP5 interface design

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.