Laravel 中间件、异常错误 - 请求网址日志记录,全局请求参数校验

Laravel改造完整版传送门

参考地址:https://learnku.com/docs/laravel/7.x/middleware/7459

上一篇日志已经将格式调整完毕,如感兴趣请移步日志篇

完整版-Laravel改造完整版传送门

配置中间件

请求网址日志记录

添加文件:app/Http/Middleware/RequestLog.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;


/**
 * Class RequestLog
 *
 * @package App\Http\Middleware
 * @author  wei
 */
class RequestLog
{
    /**
     * Handle an incoming request.
     *
     * @param Request  $request
     * @param \Closure $next
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        Log::info("Route Log");

        return $next($request);
    }
}

中间件已经制作完毕, 在app/Http/Kernel.php中添加配置

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
    	// WEB请求时使用 - 不懂得可以参考:https://blog.csdn.net/eight_eyes/article/details/110678317
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
             # 新增
            \App\Http\Middleware\RequestLog::class,
        ],

    	// API请求时使用 - 不懂得可以参考:https://blog.csdn.net/eight_eyes/article/details/110678317
        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
             # 新增
            \App\Http\Middleware\RequestLog::class,
        ],
    ];

这样每次访问的时候就可以直接记录请求了 - 不懂得可以参考:路由篇

全局请求参数校验

添加文件:app/Http/Middleware/ApiParameterVerification.php

<?php

namespace App\Http\Middleware;

use App\Exceptions\PromptException;
use Closure;
use Illuminate\Http\Request;


/**
 * Class ApiParameterVerification
 *
 * @author  wei
 * @package App\Http\Middleware
 */
class ApiParameterVerification
{
    /**
     * Handle an incoming request.
     *
     * @param Request|null $request
     * @param \Closure     $next
     *
     * @return mixed
     */
    public function handle(?Request $request, Closure $next)
    {
        if (!$request->has(['app_key', 'timestamp'])) {
        	// 自定义了一个异常 - 如果写入其中则抛出JSON错误
            throw new PromptException('prompt.parameter_verification.miss', ['app_key or timestamp']);
        }

        return $next($request);
    }
}

同样中间件已经制作完毕, 在app/Http/Kernel.php中添加配置

/**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
    	// ...

    	// API请求时使用 - 不懂得可以参考:https://blog.csdn.net/eight_eyes/article/details/110678317
        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\RequestLog::class,
            # 新增
            \App\Http\Middleware\ApiParameterVerification::class,
        ],
    ];

到这里中间件就结束了,对PromptException感兴趣的可以往下继续看

添加文件 app/Exceptions/PromptException.php

<?php

namespace App\Exceptions;


use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Utility\Helper\ConfOperation;


/**
 * Class PromptException
 *
 * @package App\Exceptions
 */
class PromptException extends \RuntimeException
{

    /**
     * PromptException constructor.
     *
     * @param string $key
     * @param array  $param
     *
     * @throws \Exception
     */
    public function __construct(string $key, array $param)
    {
        $config = ConfOperation::fillPromptCodeCfg($key, $param);

        parent::__construct($config['message'], $config['code']);

        $trace   = $this->getTrace()[0];
        $context = [
            'key'    => $key,
            'config' => $config,
            'method' => sprintf("%s::%s", $trace['class'], $trace['function']),
        ];

        Log::error(__CLASS__, $context);
    }


    /**
     * 将异常转换为 HTTP 响应。
     * 
     * 底层会自行调用
     * 1. 第一个参数为Request
     * 2. 第二个参数我翻阅源码并没有真正传入... 可能是使用方法不对,
     * 不过可以用$this来实现大部分需求
     * 
     * @return JsonResponse
     */
    public function render()
    {
        return response()->json([
            'code'    => $this->getCode(),
            'message' => $this->getMessage(),
            'data'    => null
        ]);
    }


}

添加文件 utility/Helper/ConfOperation.php

<?php


namespace Utility\Helper;


/**
 * Class ConfOperation
 *
 * @package Utility\Helper
 */
class ConfOperation
{

    /**
     * 填充配置文件
     *
     * @param string $key
     * @param array  $param
     *
     * @return string
     */
    public static function fillConf(string $key, array $param)
    {
        return vsprintf(config($key), $param);
    }


    /**
     * 填充提示Code配置
     *
     * @param string $key
     * @param array  $param
     *
     * @return array|string
     * @throws \Exception
     */
    public static function fillPromptCodeCfg(string $key, array $param)
    {
        $config = config($key);

        if (! array_key_exists('message', $config)) {
            throw new \Exception(sprintf("Key %s is not found", $key));
        }

        $config['message'] = vsprintf($config['message'], $param);

        return $config;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值