Current Location: Home> Latest Articles> Make Exception Handling in ThinkPHP6 Elegant with Whoops Integration

Make Exception Handling in ThinkPHP6 Elegant with Whoops Integration

gitbox 2025-06-26

Introduction

When developing with ThinkPHP6, it's common to encounter various runtime exceptions. By default, ThinkPHP6 displays a basic error page, which is not ideal for debugging. To enhance the developer experience, we can integrate the Whoops library, a powerful tool that presents exceptions in a more user-friendly and detailed format.

What Is Whoops?

Whoops is an open-source PHP library designed for handling exceptions and errors. It offers a visually rich and interactive error interface that includes detailed stack traces, file paths, error types, and more. Integrating Whoops into your project can significantly simplify debugging and error tracking during development.

Installing the Whoops Library

You can easily add Whoops to your project using Composer. Run the following command in your project directory:

composer require filp/whoops

Configuring Whoops in a ThinkPHP6 Project

Create Middleware

First, create a new middleware file named WhoopsFilter.php under the app directory. Here's the content:


namespace app\middleware;

use think\facade\Config;
use think\exception\Handle;

class WhoopsFilter extends Handle
{
    public function render($request, \Throwable $e)
    {
        if (Config::get('app.app_debug')) {
            $whoops = new \Whoops\Run;
            $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
            $whoops->register();
        }
        return parent::render($request, $e);
    }
}

Register the Middleware

Next, open the app/middleware.php file and register the middleware by adding it to the returned array:


return [
    // ...
    \app\middleware\WhoopsFilter::class,
    // ...
];

Enable Debug Mode

To ensure Whoops works properly, make sure the project is running in debug mode. In your config/app.php file, locate and update the following configuration:


'app_debug' => true,

Demo of the Effect

Once you've completed the setup, you can test how Whoops works. Here's an example controller method that intentionally triggers an error:


public function index()
{
    $undefinedVariable = 'Hello, Whoops!';
    echo $undefinedVariable;
}

When you access this method, you will be presented with a stylish Whoops error page that includes a complete stack trace, code context, and other helpful debugging information.

Conclusion

By integrating the Whoops library into your ThinkPHP6 project, you can replace the basic native error pages with a more advanced, visually appealing debugging tool. This makes the development process smoother and helps developers identify and resolve issues more efficiently. It’s a valuable addition for any ThinkPHP6 developer working in a debug environment.