如何使用Laravel 框架返回状态拦截

发布时间:2021-04-13 17:38:20 作者:Leah
来源:亿速云 阅读:243

如何使用Laravel 框架返回状态拦截?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

使用查询

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);
 }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. Vue中怎么使用axios请求拦截
  2. 如何在Vue中使用Express实现登录注销功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

laravel

上一篇:怎么在zf框架中使用zend_cache缓存

下一篇:使用Node.js怎么实现一个无侵入式缓存框架

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》