Laravel 框架返回状态拦截代码


Posted in PHP onOctober 18, 2019

可拦截系统的返回的状态自己在单独处理。

使用查询

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
<?php
 
namespace App\Exceptions;
 
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\QueryException;
use App\Traits\Response\InterfaceResponse;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
 
/**
 * 异常处理
 *
 * Date: 21/03/2018
 * @author George
 * @package App\Exceptions
 */
class Handler extends ExceptionHandler
{
	use InterfaceResponse;
 
 /**
  * 定义不需要记录的异常类
  *
  * @var array
  */
 protected $dontReport = [
		HttpException::class,
		ValidationException::class,
		ModelNotFoundException::class,
		AuthorizationException::class,
		AuthenticationException::class,
	];
 
 /**
  * A list of the inputs that are never flashed for validation exceptions.
  *
  * @var array
  */
 protected $dontFlash = [
  'password',
  'password_confirmation',
 ];
 
	/**
	 * 定义需要记录的异常
	 *
	 * Date: 21/03/2018
	 * @author George
	 * @param Exception $exception
	 * @return mixed|void
	 * @throws Exception
	 */
 public function report(Exception $exception)
 {
  parent::report($exception);
 }
 
	/**
	 * 拦截异常并生成对应的响应内容
	 *
	 * Date: 21/03/2018
	 * @author George
	 * @param \Illuminate\Http\Request $request
	 * @param Exception $exception
	 * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
	 */
 public function render($request, Exception $exception)
 {
 	// 拦截数据库操作异常
// 	if ($exception instanceof QueryException) {
// 		Log::error($exception);
// 		return $this->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 框架返回状态拦截代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
详细介绍PHP应用提速面面观
Oct 09 PHP
对text数据类型不支持代码页转换 从: 1252 到: 936
Apr 23 PHP
php file_put_contents()功能函数(集成了fopen、fwrite、fclose)
May 24 PHP
用PHP实现小写金额转换大写金额的代码(精确到分)
Jan 10 PHP
thinkphp3.2中Lite文件替换框架入口文件或应用入口文件的方法
May 21 PHP
php冒泡排序与快速排序实例详解
Dec 07 PHP
thinkPHP的表达式查询用法详解
Sep 14 PHP
PHP根据树的前序遍历和中序遍历构造树并输出后序遍历的方法
Nov 10 PHP
php单元测试phpunit入门实例教程
Nov 17 PHP
php使用mysqli和pdo扩展,测试对比连接mysql数据库的效率完整示例
May 09 PHP
php数组和链表的区别总结
Sep 20 PHP
PHP用swoole+websocket和redis实现web一对一聊天
Nov 05 PHP
laravel 解决groupBy时出现的错误 isn't in Group By问题
Oct 17 #PHP
Mac下关于PHP环境和扩展的安装详解
Oct 17 #PHP
mac pecl 安装php7.1扩展教程
Oct 17 #PHP
浅谈laravel框架sql中groupBy之后排序的问题
Oct 17 #PHP
Laravel框架中集成MongoDB和使用详解
Oct 17 #PHP
解决laravel中日志权限莫名变成了root的问题
Oct 17 #PHP
关于laravel 日志写入失败问题汇总
Oct 17 #PHP
You might like
PHP跨时区(UTC时间)应用解决方案
2013/01/11 PHP
WordPress中获取指定分类及其子分类下的文章数目
2015/12/31 PHP
js将当前时间格式转换成时间搓(自写)
2013/09/26 Javascript
纯js分页代码(简洁实用)
2013/11/05 Javascript
Javascript 读取操作Sql中的Xml字段
2014/10/09 Javascript
浅析Javascript ES6新增值比较函数Object.is
2016/08/24 Javascript
javascript轮播图算法
2016/10/21 Javascript
BootStrap3中模态对话框的使用
2017/01/06 Javascript
jQuery判断邮箱格式对错实例代码讲解
2017/04/12 jQuery
用js将long型数据转换成date型或datetime型的实例
2017/07/03 Javascript
jquery实现加载更多&quot;转圈圈&quot;效果(示例代码)
2020/11/09 jQuery
Python实现优先级队列结构的方法详解
2016/06/02 Python
Django 生成登陆验证码代码分享
2017/12/12 Python
Python实现深度遍历和广度遍历的方法
2019/01/22 Python
python3.x实现base64加密和解密
2019/03/28 Python
Python从函数参数类型引出元组实例分析
2019/05/28 Python
python-tkinter之按钮的使用,开关方法
2019/06/11 Python
Python Web程序搭建简单的Web服务器
2019/07/31 Python
python的pyecharts绘制各种图表详细(附代码)
2019/11/11 Python
详解字符串在Python内部是如何省内存的
2020/02/03 Python
python的链表基础知识点
2020/09/13 Python
一款纯css3实现的响应式导航
2014/10/31 HTML / CSS
html5 video标签屏蔽右键视频另存为的js代码
2013/11/12 HTML / CSS
HTML5+CSS3实现机器猫
2016/10/17 HTML / CSS
HTML5 canvas实现的静态循环滚动播放弹幕
2021/01/05 HTML / CSS
经理秘书岗位职责
2013/11/14 职场文书
职工趣味运动会方案
2014/02/10 职场文书
个性发展自我评价
2014/02/11 职场文书
培训通知书模板
2015/04/17 职场文书
2015年会计工作总结范文
2015/05/26 职场文书
夏洛特的网观后感
2015/06/15 职场文书
结婚喜宴迎宾词
2015/08/10 职场文书
导游词之云南-元阳梯田
2019/10/08 职场文书
pytorch实现线性回归以及多元回归
2021/04/11 Python
MySQL中你可能忽略的COLLATION实例详解
2021/05/12 MySQL
详解Spring Bean的配置方式与实例化
2022/06/10 Java/Android