laravel:自定义异常(10.27.0)
一,创建exception:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan make:exception ApiException
INFO Exception [app/Exceptions/ApiException.php] created successfully.
二,php代码:
1,在新添加的异常类app/Exceptions/ApiException中添加代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<?phpnamespace App\Exceptions;use Exception;use Throwable;class ApiException extends Exception{ public function __construct($message = "", $code = 400, Throwable $previous = null) { parent::__construct($message, $code, $previous); } public function render() { return response()->json([ 'msg' => $this->message, 'code' => $this->code, ]); }} |
2,controller中抛出异常
|
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
|
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use Illuminate\Support\Facades\App;use App\extend\result\Result;use App\Exceptions\ApiException;class NewsController extends Controller{ //使用统一返回的数据格式 public function res(Request $request) { throw new ApiException('该商品不存在',1024); //判断是否存在name参数,如果存在 if ($request->has('name')) { $data = [ 'name'=>$request->name, 'age'=>'24', ]; return Result::Success($data); } else { //参数不存在时返回错误 return Result::ErrorCode(10024,'缺少name参数'); } } |
三,测试效果

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/17/laravel-zi-ding-yi-yi-chang-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号