laravel:异常时返回json(10.27.0)
一,相关文档:
https://learnku.com/docs/laravel/10.x/errors/14857#87364d
二,php代码:
1,app\exceptions\Handler.php
增加以下一段:
|
1
2
3
4
5
6
7
8
9
10
11
|
//重写renderpublic function render($request, Throwable $e){ if (env('APP_DEBUG')) { return parent::render($request, $e); } return response()->json([ 'msg' => $e->getMessage(), 'code' => $e->getCode(), ]);} |
2,在controller中添加一个除0错代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class NewsController extends Controller{ //使用统一返回的数据格式 public function res(Request $request) { $res = 10 / 0; //判断是否存在name参数,如果存在 if ($request->has('name')) { $data = [ 'name'=>$request->name, 'age'=>'24', ]; return Result::Success($data); } else { //参数不存在时返回错误 return Result::ErrorCode(10024,'缺少name参数'); } } |
三,测试效果
默认的报错页面:

配置返回json后:

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/17/laravel-yi-chang-shi-fan-hui-json-10-27/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
四,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0

浙公网安备 33010602011771号