【laravel5.6】 laravel 接口 接管 自定义异常类
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【laravel5.6】 laravel 接口 接管 自定义异常类,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1989字,纯文字阅读大概需要3分钟。
内容图文
![【laravel5.6】 laravel 接口 接管 自定义异常类](/upload/InfoBanner/zyjiaocheng/1296/8279b3ad7bf44d6898ce02cdb2fec597.jpg)
1 app\exceptions 目录下 新建 Apiexception.php
<?php namespace App\Exceptions; /*** * API 自定义异常类 */ use Exception; class ApiException extends Exception { //自定义异常处理public function SetErrorMessage($errorMsg=‘‘, $errorCode = ‘500‘){ $this->errorMsg = $errorMsg; $this->errorCode = $errorCode; return $this; } }
2 修改 app\exceptions\handler.php 文件
/* * * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { // 如果config配置debug为true ==>debug模式的话让laravel自行处理 $debug_status = config(‘app.debug‘); // .env文件配置if($debug_status){ return parent::render($request, $exception); } return $this->handle($request, $exception); } /** * 异常接管 * */public function handle($request, Exception $exception){ //如果是接口请求,则抛出jsonif($request->is(‘api/*‘)) { // 只处理自定义的APIException异常 if($exception instanceof \APP\Exceptions\ApiException ) { //此处写ApiException文件所处路径 $result = [ "status" => 2 , //操作状态: 1 成功 2 失败"errorCode"=>$exception->errorCode, "msg" => $exception->errorMsg, "result" => ‘‘, ]; return response()->json($result); } //此处可以写多个自定义异常类if($exception instanceof \APP\Exceptions\otherException ) { $result = [ "status" => 2 , //操作状态: 1 成功 2 失败"errorCode"=>$exception->errorCode, "msg" => $exception->errorMsg, "result" => ‘‘, ]; return response()->json($result); } # 继续写其他自定义异常 /*** * code * * ***/ } return parent::render($request, $exception); }
3 使用
<?php namespace App\Http\Controllers\Test; use Illuminate\Routing\Controller; use App\Exceptions\ApiException; class IndexController extends Controller { public function index(){ throw (new ApiException)->SetErrorMessage("错了",‘500‘); } }
这就ok了
整体思路: 使用时候,先实例 自定义 异常。把错误信息传过去, 然后会回到 handler.php 里边显示
注意事项:
1 测试时候。要注册一个路由在访问
2 注意开启debug 在.env 文件里边
原文:https://www.cnblogs.com/richerdyoung/p/10044760.html
内容总结
以上是互联网集市为您收集整理的【laravel5.6】 laravel 接口 接管 自定义异常类全部内容,希望文章能够帮你解决【laravel5.6】 laravel 接口 接管 自定义异常类所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。