webman:配置异常处理返回json格式(v1.5.7)
一,添加一个除0错的异常代码:
页面显示效果如图:
二,配置:
php代码
1,config/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?php /** * This file is part of webman. * * Licensed under The MIT License * For full copyright and license information, please see the MIT-LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @author walkor<walkor@workerman.net> * @copyright walkor<walkor@workerman.net> * @link http://www.workerman.net/ * @license http://www.opensource.org/licenses/mit-license.php MIT License */ //指定异常处理类的路径 return [ //'' => support\exception\Handler::class, '' => app\exception\ExceptionHandler:: class , ]; |
2,app/exception/ExceptionHandler.php
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
|
<?php namespace app\exception; use Webman\Exception\ExceptionHandler as Handle; use Webman\Http\Request; use Webman\Http\Response; use Throwable; class ExceptionHandler extends Handle { private $code ; private $status ; private $msg ; /** * 记录异常信息(包括日志或者其它方式记录) * * @access public * @param Throwable $exception * @return void */ public function report(Throwable $exception ): void { // 使用内置的方式记录异常日志 parent::report( $exception ); } public function render(Request $request , Throwable $e ): Response { $result = [ 'code' => $e ->getCode(), 'message' => $e ->getMessage(), 'file' => $e ->getFile(), 'uri' => $request ->uri(), 'url' => $request ->fullUrl(), ]; return json( $result ); } } |
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/08/19/webman-pei-zhi-yi-chang-chu-li-fan-hui-json-ge-shi/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
三,测试效果:
四,查看webman版本:
liuhongdi@lhdpc:/data/webman/imageadmin$ composer show workerman/webman-framework
name : workerman/webman-framework
descrip. : High performance HTTP Service Framework.
keywords : High Performance, http service
versions : * v1.5.7
...