您现在的位置是:网站首页> 编程资料编程资料
Laravel 框架返回状态拦截代码_php实例_
2023-05-25
267人已围观
简介 Laravel 框架返回状态拦截代码_php实例_
可拦截系统的返回的状态自己在单独处理。
使用查询
composer require betterde/response // 安装后直接调用以下 # stored return stored($data, $message = '创建成功'); #updated return updated($data, $message = '更新成功'); #deleted return deleted($message = '删除成功'); #accepted return accepted($message = '请求已接受,等待处理'); #notFound return notFound($message = '您访问的资源不存在'); #internalError return internalError($message = '未知错误导致请求失败'); #failed return failed($message, $code = Response::HTTP_BAD_REQUEST); #success return success($data); #message return message($message, $code = Response::HTTP_OK); #respond return respond($data = [], $message = '请求成功', array $header = []);
拦截代码
App\Exceptions\Handler
internalError(); // } // 拦截一般异常并生成响应 if ($exception instanceof GeneralException) { return failed($exception->getMessage(), $exception->getCode() ?: 500); } // 拦截404异常 if ($exception instanceof ModelNotFoundException) { return $this->notFound(); } // 拦截授权异常 if ($exception instanceof AuthorizationException) { return failed('您无权访问', 403); } // 参数验证错误的异常,我们需要返回 400 的 http code 和一句错误信息 if ($exception instanceof ValidationException) { return failed(array_first(array_collapse($exception->errors())), 422); } // 用户认证的异常,我们需要返回 401 的 http code 和错误信息 if ($exception instanceof UnauthorizedHttpException) { return failed('未提供Token', 401); } // 捕获404异常 if ($exception instanceof NotFoundHttpException) { return $this->notFound(); } return parent::render($request, $exception); } /** * 认证失败后抛出异常 * * Date: 2018/5/27 * @author George * @param \Illuminate\Http\Request $request * @param AuthenticationException $exception * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response */ public function unauthenticated($request, AuthenticationException $exception) { return failed('身份认证失败', 401); } } 以上这篇Laravel 框架返回状态拦截代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
相关内容
- laravel 解决groupBy时出现的错误 isn't in Group By问题_php实例_
- Mac下关于PHP环境和扩展的安装详解_php技巧_
- mac pecl 安装php7.1扩展教程_php技巧_
- 浅谈laravel框架sql中groupBy之后排序的问题_php实例_
- Laravel框架中集成MongoDB和使用详解_php实例_
- 解决laravel中日志权限莫名变成了root的问题_php实例_
- 关于laravel 日志写入失败问题汇总_php实例_
- 自定义Laravel (monolog)日志位置,并增加请求ID的实现_php实例_
- 详解Laravel设置多态关系模型别名的方式_php实例_
- PHP实现简单登录界面_php实例_
