title: Error and exception interception meta:

  • name: description content: Easyswoole,Error and exception interception
  • name: keywords content: swoole|swoole extension|swoole framework|EasySwoole|Error and exception interception|Swoole error exception

Error and exception interception

Http controller error exception

An error occurs in the http controller, the system will use the default exception handling to output to the client, the code is as follows:

  1. <?php
  2. protected function hookThrowable(\Throwable $throwable,Request $request,Response $response)
  3. {
  4. if(is_callable($this->httpExceptionHandler)){
  5. call_user_func($this->httpExceptionHandler,$throwable,$request,$response);
  6. }else{
  7. $response->withStatus(Status::CODE_INTERNAL_SERVER_ERROR);
  8. $response->write(nl2br($throwable->getMessage()."\n".$throwable->getTraceAsString()));
  9. }
  10. }

Can override the onException method directly on the controller:

  1. <?php
  2. namespace App\HttpController;
  3. use App\ViewController;
  4. use EasySwoole\Http\AbstractInterface\Controller;
  5. use EasySwoole\Http\Message\Status;
  6. class Base extends ViewController
  7. {
  8. function index()
  9. {
  10. // TODO: Implement index() method.
  11. $this->actionNotFound('index');
  12. }
  13. function onException(\Throwable $throwable): void
  14. {
  15. var_dump($throwable->getMessage());
  16. }
  17. protected function actionNotFound(?string $action): void
  18. {
  19. $this->response()->withStatus(Status::CODE_NOT_FOUND);
  20. $this->response()->write('action not found');
  21. }
  22. }

Can also customize exception handling files:

  1. <?php
  2. namespace App;
  3. use EasySwoole\Http\Request;
  4. use EasySwoole\Http\Response;
  5. class ExceptionHandler
  6. {
  7. public static function handle( \Throwable $exception, Request $request, Response $response )
  8. {
  9. var_dump($exception->getTraceAsString());
  10. }
  11. }

DI registration exception handling in the initialize event:

  1. public static function initialize()
  2. {
  3. Di::getInstance()->set(SysConst::HTTP_EXCEPTION_HANDLER,[ExceptionHandler::class,'handle']);
  4. }