错误与异常拦截

http 控制器错误异常

http 控制器中出现错误,系统将使用默认异常处理进行输出至客户端,代码如下:

  1. <?php
  2. protected function onException(\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. }

可直接在控制器重写 onException 方法:

  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. }

自定义异常处理

开发者可自定义异常处理文件:

  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. }

initialize 事件中使用 DI 注册异常处理:

  1. <?php
  2. public static function initialize()
  3. {
  4. \EasySwoole\Component\Di::getInstance()->set(\EasySwoole\EasySwoole\SysConst::HTTP_EXCEPTION_HANDLER, [\App\ExceptionHandler::class, 'handle']);
  5. }