1. register listener
Config/autoload/listeners.php is as follows
declare(strict_types=1); /** * This file is part of Hyperf. * * @link https://www.hyperf.io * @document https://hyperf.wiki * @contact [email protected] * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ return [ \Hyperf\ExceptionHandler\Listener\ErrorExceptionHandler::class ];
Hyperf\exceptionhandler\listener\errorexception handler:: class, error_reporting() Error level listener.
Refer to the listener chapter on the official website https://hyperf.wiki/2.2/#/zh -cn/exception-handler
2. Register global Middleware
Now configure the middleware under config/autoload/middleware.php
<?php declare(strict_types=1); namespace App\Middleware\Auth; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse; class FooMiddleware implements MiddlewareInterface { /** * @var ContainerInterface */ protected $container; /** * @var HttpResponse */ protected $response; public function __construct(ContainerInterface $container, HttpResponse $response) { $this->container = $container; $this->response = $response; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { try { return $handler->handle($request); } catch (\Throwable $throwable) { return $this->response->json( [ 'code' => -1, 'message' => $throwable->getMessage(), 'data' => [ ], ] ); } } }
After completing the above steps, you can return PHP error prompts such as notice to the front end, and the PHP program will not continue to execute.