如何在中间件中捕获"too many attempt"异常 Laravel 5



我正在构建我的 API,我成功地在围绕我的路由设置的中间件上捕获了一些错误,如下所示:

Route::group(['middleware' => AppHttpMiddlewareExceptionHandlerMiddleware::class], function() {
Route::resource('/address', 'AddressController');
Route::resource('/country', 'CountryController');
Route::resource('/phone', 'PhoneController');
Route::resource('/user', 'UserController');
});

中间件设法捕获以下异常:

  • IlluminateDatabaseEloquentModelNotFoundException
  • IlluminateValidationValidationException
  • Exception

这很好。我也知道控制路线尝试次数的油门机制。因此,我与邮递员一起攻击了我的路线http://localhost:8000/api/user直到我得到too many attemp错误。

异常在位于 的文件中引发:

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

由于这个论坛主题,我还设法获得了它引发的异常类型:SymfonyComponentHttpKernelExceptionTooManyRequestsHttpException.

所以最后我的中间件看起来像这样:

<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateDatabaseEloquentModelNotFoundException;
use IlluminateValidationValidationException;
use SymfonyComponentHttpKernelExceptionTooManyRequestsHttpException;
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 的原始油门例外总是走在前面。

问题

我怎样才能正确地覆盖基本错误,使我可能(如果可能的话(捕获任何异常而无需修改照明文件(在更新的情况下......

运行拉拉维尔 5.4。

编辑

我负担不起手动更新app/Http/Exception文件的费用,因为我的应用程序将作为服务提供商交付给我的未来其他项目。此外,我不喜欢冒险擦除这些文件上的一些先前配置,因为routes.php中的其他"基本"路由可能有自己的异常捕获过程。

实现这一目标的最佳方法是使用appExceptionsHandler.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) {(并解决它们。

最新更新