Thinkphp 在api开发中异常返回依然是html的解决方式

2025-05-27 0 17

现在谁不开发接口的呢?但是在接口开发过程中,报错误html\”>异常后居然返回错误的信息依然是html信息!TP官方也不知道为啥不添加,说好的为接口而生,我的解决方案也很简单,把系统的异常处理类复制出来,去掉模板相关,直接以json方式输出

下面是解决方案:

1:按照TP扩展异常的方式引用这个文件

https://www.kancloud.cn/manual/thinkphp5_1/354092

?

1

2

3

4

5

6

7
// 判断默认输出类型

// $app 是配置数组

if ($app['default_return_type'] == 'json') {

// 异常处理handle类 留空使用 \\think\\exception\\Handle

$app['exception_handle'] = '\\\\app\\\\common\\\\exception\\\\JsonException';

}

return $app;

异常处理类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297
<?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的解决方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/dragonlhp/article/details/79263925

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Thinkphp 在api开发中异常返回依然是html的解决方式 https://www.kuaiidc.com/71002.html

相关文章

发表评论
暂无评论