|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace think\Whoops; |
| 6 | + |
| 7 | +use think\exception\Handle; |
| 8 | +use think\exception\HttpResponseException; |
| 9 | +use think\Response; |
| 10 | +use Throwable; |
| 11 | +use Whoops\Handler\PrettyPageHandler; |
| 12 | + |
| 13 | +class RenderExceptionWithWhoops extends Handle |
| 14 | +{ |
| 15 | + public function render($request, Throwable $e): Response |
| 16 | + { |
| 17 | + // Whoops 接管请求异常 |
| 18 | + if (config('whoops.enable') && $this->app->isDebug()) { |
| 19 | + if ($e instanceof HttpResponseException) { |
| 20 | + return $e->getResponse(); |
| 21 | + } |
| 22 | + |
| 23 | + // 兼容 Cors Postman 请求 |
| 24 | + // $request->isAjax() 判断不太正常 |
| 25 | + if ($request->isJson() || false !== strpos($_SERVER['HTTP_USER_AGENT'], 'Postman') || (isset($_SERVER['HTTP_SEC_FETCH_MODE']) && $_SERVER['HTTP_SEC_FETCH_MODE'] === 'cors')) { |
| 26 | + return $this->handleAjaxException($e); |
| 27 | + } |
| 28 | + |
| 29 | + $this->app->whoops->pushHandler(new PrettyPageHandler()); |
| 30 | + return Response::create( |
| 31 | + $this->app->whoops->handleException($e), |
| 32 | + 'html', |
| 33 | + $e->getCode() |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + // 其他错误交给系统处理 |
| 38 | + return parent::render($request, $e); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * 接管Ajax异常. |
| 43 | + * |
| 44 | + * @param Throwable $e |
| 45 | + * |
| 46 | + * @return void |
| 47 | + */ |
| 48 | + protected function handleAjaxException(Throwable $e) |
| 49 | + { |
| 50 | + $data = [ |
| 51 | + 'name' => get_class($e), |
| 52 | + 'file' => $e->getFile(), |
| 53 | + 'line' => $e->getLine(), |
| 54 | + 'message' => $this->getMessage($e), |
| 55 | + 'trace' => $e->getTrace(), |
| 56 | + 'code' => $this->getCode($e), |
| 57 | + 'source' => $this->getSourceCode($e), |
| 58 | + 'datas' => $this->getExtendData($e), |
| 59 | + 'tables' => [ |
| 60 | + 'GET Data' => $this->app->request->get(), |
| 61 | + 'POST Data' => $this->app->request->post(), |
| 62 | + 'Files' => $this->app->request->file(), |
| 63 | + 'Cookies' => $this->app->request->cookie(), |
| 64 | + 'Session' => $this->app->session->all(), |
| 65 | + 'Server/Request Data' => $this->app->request->server(), |
| 66 | + 'Environment Variables' => $this->app->request->env(), |
| 67 | + 'ThinkPHP Constants' => $this->getConst(), |
| 68 | + ], |
| 69 | + ]; |
| 70 | + |
| 71 | + return Response::create($data, 'json', $e->getCode()); |
| 72 | + } |
| 73 | +} |
0 commit comments