簡體   English   中英

如何在中間件Laravel 5中捕獲“太多嘗試”異常

[英]How to catch “too many attempt” exception in a middleware Laravel 5

我正在構建自己的API,並且成功設法在圍繞路由設置的中間件上捕獲了一些錯誤,如下所示:

Route::group(['middleware' => \App\Http\Middleware\ExceptionHandlerMiddleware::class], function() {

    Route::resource('/address', 'AddressController');

    Route::resource('/country', 'CountryController');

    Route::resource('/phone', 'PhoneController');

    Route::resource('/user', 'UserController');
});

中間件設法捕獲以下異常:

  • Illuminate\\Database\\Eloquent\\ModelNotFoundException
  • Illuminate\\Validation\\ValidationException
  • Exception

太好了 我也知道節流機制可以控制路線中的嘗試次數。 因此,我使用郵遞員攻擊了我的路線http://localhost:8000/api/user直到收到too many attemp錯誤。

異常拋出在位於的文件中:

/vendor/laravel/framework/src/Illuminate/Routing/Middleware/ThrottleRequests.php

由於這個論壇主題 ,我也設法獲得了引發的異常類型: Symfony\\Component\\HttpKernel\\Exception\\TooManyRequestsHttpException

所以最后我的中間件看起來像這樣:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
use Exception;

class ExceptionHandlerMiddleware
{
    public function handle($request, Closure $next)
    {
        $output = $next($request);

        try {
            if( ! is_null( $output->exception ) ) {
                throw new $output->exception;
            }

            return $output;
        }
        catch( TooManyRequestsHttpException $e ) {
            return response()->json('this string is never showed up', 429);
        }
        catch( ValidationException $e ) {           
            return response()->json('validation error' 400);
        }
        catch( ModelNotFoundException $e ) {            
            return response()->json('not found', 404);
        }
        catch( \Exception $e ) {            
            return response()->json('unknow', 500);
        }
    }
}

您看到this string is never showed up嗎? 實際上,它從未出現過,Illuminate最初的節氣門例外總是占據前列。

如何以一種可能的方式(如果可能的話)捕獲任何異常而無需修改照明文件(在進行更新的情況下)正確地覆蓋基本錯誤?

運行laravel 5.4。

編輯

我負擔不起手動更新app/Http/Exception文件,因為我的應用程序將作為我的期貨其他項目的服務提供商提供。 另外,我也不希望冒險刪除這些文件上的某些先前配置,因為routes.php其他“基本”路由可能具有自己的異常捕獲過程。

最好的方法是使用app\\Exceptions\\Handler.php

public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception)) {
        if (request()->expectsJson()) {
            switch ($exception->getStatusCode()) {
                case 404:
                    return response()->json(['message' => 'Invalid request or url.'], 404);
                    break;
                case '500':
                    return response()->json(['message' => 'Server error. Please contact admin.'], 500);
                    break;

                default:
                    return $this->renderHttpException($exception);
                    break;
            }
        }
    } else if ($exception instanceof ModelNotFoundException) {
        if (request()->expectsJson()) {
            return response()->json(['message' =>$exception->getMessage()], 404);
        }
    } {
        return parent::render($request, $exception);
    }
    return parent::render($request, $exception);
}

在這個演示中,您可以添加更多的異常,例如} else if ($exception instanceof ModelNotFoundException) {並解決它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM