错误与异常拦截

http控制器错误异常

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

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

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

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

也可自定义异常处理文件:

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