您好,登錄后才能下訂單哦!
這篇文章主要介紹Thinkphp在api開發中異常返回依然是html怎么辦,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
現在誰不開發接口的呢?但是在接口開發過程中,報錯誤異常后居然返回錯誤的信息依然是html信息!TP官方也不知道為啥不添加,說好的為接口而生,我的解決方案也很簡單,把系統的異常處理類復制出來,去掉模板相關,直接以json方式輸出
下面是解決方案:
1:按照TP擴展異常的方式引用這個文件
// 判斷默認輸出類型 // $app 是配置數組 if ($app['default_return_type'] == 'json') { // 異常處理handle類 留空使用 \think\exception\Handle $app['exception_handle'] = '\\app\\common\\exception\\JsonException'; } return $app;
異常處理類:
<?php namespace app\common\exception; use Exception; use think\exception\ErrorException; use think\exception\Handle; use think\exception\HttpException; use think\console\Output; use think\Container; use think\Response; class JsonException extends Handle { protected $render; protected $ignoreReport = [ '\\think\\exception\\HttpException', ]; public function setRender($render) { $this->render = $render; } /** * Report or log an exception. * * @access public * @param \Exception $exception * @return void */ public function report(Exception $exception) { if (!$this->isIgnoreReport($exception)) { // 收集異常數據 if (Container::get('app')->isDebug()) { $data = [ 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'message' => $this->getMessage($exception), 'code' => $this->getCode($exception), ]; $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]"; } else { $data = [ 'code' => $this->getCode($exception), 'message' => $this->getMessage($exception), ]; $log = "[{$data['code']}]{$data['message']}"; } if (Container::get('app')->config('log.record_trace')) { $log .= "\r\n" . $exception->getTraceAsString(); } Container::get('log')->record($log, 'error'); } } protected function isIgnoreReport(Exception $exception) { foreach ($this->ignoreReport as $class) { if ($exception instanceof $class) { return true; } } return false; } /** * Render an exception into an HTTP response. * * @access public * @param \Exception $e * @return Response */ public function render(Exception $e) { if ($this->render && $this->render instanceof \Closure) { $result = call_user_func_array($this->render, [$e]); if ($result) { return $result; } } if ($e instanceof HttpException) { return $this->renderHttpException($e); } else { return $this->convertExceptionToResponse($e); } } /** * @access public * @param Output $output * @param Exception $e */ public function renderForConsole(Output $output, Exception $e) { if (Container::get('app')->isDebug()) { $output->setVerbosity(Output::VERBOSITY_DEBUG); } $output->renderException($e); } /** * @access protected * @param HttpException $e * @return Response */ protected function renderHttpException(HttpException $e) { $status = $e->getStatusCode(); $template = Container::get('app')->config('http_exception_template'); if (!Container::get('app')->isDebug() && !empty($template[$status])) { return Response::create($e, 'json', $status); } else { return $this->convertExceptionToResponse($e); } } /** * @access protected * @param Exception $exception * @return Response */ protected function convertExceptionToResponse(Exception $exception) { // 收集異常數據 if (Container::get('app')->isDebug()) { // 調試模式,獲取詳細的錯誤信息 $data = [ 'name' => get_class($exception), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'message' => $this->getMessage($exception), 'trace' => $exception->getTrace(), 'code' => $this->getCode($exception), 'source' => $this->getSourceCode($exception), 'datas' => $this->getExtendData($exception), 'tables' => [ 'GET Data' => $_GET, 'POST Data' => $_POST, 'Files' => $_FILES, 'Cookies' => $_COOKIE, 'Session' => isset($_SESSION) ? $_SESSION : [], 'Server/Request Data' => $_SERVER, 'Environment Variables' => $_ENV, 'ThinkPHP Constants' => $this->getConst(), ], ]; } else { // 部署模式僅顯示 Code 和 Message $data = [ 'code' => $this->getCode($exception), 'message' => $this->getMessage($exception), ]; if (!Container::get('app')->config('show_error_msg')) { // 不顯示詳細錯誤信息 $data['message'] = Container::get('app')->config('error_message'); } } //保留一層 while (ob_get_level() > 1) { ob_end_clean(); } $data['echo'] = ob_get_clean(); $response = Response::create($data, 'json'); if ($exception instanceof HttpException) { $statusCode = $exception->getStatusCode(); $response->header($exception->getHeaders()); } if (!isset($statusCode)) { $statusCode = 500; } $response->code($statusCode); return $response; } /** * 獲取錯誤編碼 * ErrorException則使用錯誤級別作為錯誤編碼 * @access protected * @param \Exception $exception * @return integer 錯誤編碼 */ protected function getCode(Exception $exception) { $code = $exception->getCode(); if (!$code && $exception instanceof ErrorException) { $code = $exception->getSeverity(); } return $code; } /** * 獲取錯誤信息 * ErrorException則使用錯誤級別作為錯誤編碼 * @access protected * @param \Exception $exception * @return string 錯誤信息 */ protected function getMessage(Exception $exception) { $message = $exception->getMessage(); if (PHP_SAPI == 'cli') { return $message; } $lang = Container::get('lang'); if (strpos($message, ':')) { $name = strstr($message, ':', true); $message = $lang->has($name) ? $lang->get($name) . strstr($message, ':') : $message; } elseif (strpos($message, ',')) { $name = strstr($message, ',', true); $message = $lang->has($name) ? $lang->get($name) . ':' . substr(strstr($message, ','), 1) : $message; } elseif ($lang->has($message)) { $message = $lang->get($message); } return $message; } /** * 獲取出錯文件內容 * 獲取錯誤的前9行和后9行 * @access protected * @param \Exception $exception * @return array 錯誤文件內容 */ protected function getSourceCode(Exception $exception) { // 讀取前9行和后9行 $line = $exception->getLine(); $first = ($line - 9 > 0) ? $line - 9 : 1; try { $contents = file($exception->getFile()); $source = [ 'first' => $first, 'source' => array_slice($contents, $first - 1, 19), ]; } catch (Exception $e) { $source = []; } return $source; } /** * 獲取異常擴展信息 * 用于非調試模式html返回類型顯示 * @access protected * @param \Exception $exception * @return array 異常類定義的擴展數據 */ protected function getExtendData(Exception $exception) { $data = []; if ($exception instanceof \think\Exception) { $data = $exception->getData(); } return $data; } /** * 獲取常量列表 * @access private * @return array 常量列表 */ private static function getConst() { $const = get_defined_constants(true); return isset($const['user']) ? $const['user'] : []; } }
以上是“Thinkphp在api開發中異常返回依然是html怎么辦”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。