Home  >  Article  >  PHP Framework  >  Finally successfully used whoops to take over the exception handling of tp6!

Finally successfully used whoops to take over the exception handling of tp6!

藏色散人
藏色散人forward
2021-03-05 14:00:592765browse

The following tutorial column from thinkphp will introduce to you how to use whoops to take over the exception handling of tp6. I hope it will be helpful to friends in need!

Say goodbye to the abnormal pages of ThinkPHP6, let us embrace whoops!

I got familiar with TP6 during the Spring Festival, and also wrote a TP6 blog program, but the system's exception page is really a headache, and many times it cannot be viewed. Which line of code is the problem?

So I really wanted to introduce whoops. After a series of research, I finally found the solution:

1. Install whoops through composer

Run the command: composer require filp/whoops

Note: If the file imported by composer has syntax errors, you need to deal with the syntax errors in advance before installation, otherwise an error will always be reported.

2. Use whoops to take over the exception handling of tp6

Add the following code to the render() method of the /app/ExceptionHandle.php file:

// 添加自定义异常处理机制
if (ENV('APP_DEBUG')) {
    // 如果是HttpResponseException异常则原样输出
    // JUMP插件里的success,error和result方法均返回的是HttpResponseException异常
    if ($e instanceof HttpResponseException) {
        return $e->getResponse();
    }

    // Whoops 接管请求异常
    $whoops = new \Whoops\Run;
    $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler());
    return Response::create(
        $whoops->handleException($e),
        'html',
        500
    );
}

As shown below:

Finally successfully used whoops to take over the exception handling of tp6!

3. Take a look at the result

I wrote an Non-existent function:

Finally successfully used whoops to take over the exception handling of tp6!

Refresh the page and see, OK

Finally successfully used whoops to take over the exception handling of tp6!

OK. The familiar whoops is back .

4. Postscript

In order to use whoops in thinkphp6, I carefully looked at the exception mechanism in PHP7 and finally introduced whoops. .

In the process of learning exception handling, I also found that try()catch() should be used for business processing in PHP7 instead of if()else().

I will write a separate article later to tell about my experience in studying the exceptions of PHP7.

I also hope that everyone can continue to pay attention to my blog http://laoliu.pro

Original link: http://laoliu.pro/php/6.html

The above is the detailed content of Finally successfully used whoops to take over the exception handling of tp6!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete