我正在使用 Laravel 5 和 Dingo 构建 API。我如何捕获任何没有定义路由的请求?我希望我的 API 始终以特定格式的 JSON 响应进行响应。
例如,如果我有一条路线: $api->get('somepage','mycontroller@mymethod');
如果有人在假设未定义路由的情况下向同一 uri 创建帖子,我该如何处理?
本质上,Laravel 正在抛出 MethodNotAllowedHttpException。
我试过这个:
Route::any('/{all}', function ($all)
{
$errorResponse = [
'Message' => 'Error',
'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
];
return Response::json($errorResponse, 400); //400 = Bad Request
})->where(['all' => '.*']);
但我不断抛出 MethodNotAllowedHttpException。
我有办法做到这一点吗?使用中间件?其他形式的捕获所有路线?
编辑:
尝试将其添加到 app\Exceptions\Handler.php
public function render($request, Exception $e)
{
dd($e);
if ($e instanceof MethodNotAllowedHttpException) {
$errorResponse = [
'Message' => 'Error',
'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
];
return Response::json($errorResponse, 400);
}
return parent::render($request, $e);
}
没有效果。我做了 dump-autoload 等等。我什至添加了 dd($e) 但它没有任何效果。这对我来说似乎很奇怪。
编辑 - 解决方案
想通了。虽然 James 的回答让我朝着正确的方向思考,但实际情况是 Dingo 覆盖了错误处理。为了自定义此错误的响应,您必须修改 app\Providers\AppServiceProvider.php。使引导功能像这样(默认为空)
public function boot()
{
app('Dingo\Api\Exception\Handler')->register(function (MethodNotAllowedHttpException $exception) {
$errorResponse = [
'Message' => 'Error',
'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
];
return Response::make($errorResponse, 400);
});
}
接受 James 的回答,因为它让我朝着正确的方向前进。
希望这对某人有所帮助 :) 这占据了我晚上的大部分时间......呃
最佳答案
您可以在 app/Exceptions/Handler.php
中执行此操作,方法是捕获异常并检查它是否是 MethodNotAllowedHttpException
的实例。
如果是,那么您可以执行返回自定义错误响应的逻辑。
在同一位置,如果您想捕获 NotFoundHttpException
的实例,您还可以自定义检查。
// app/Exceptions/Handler.php
public function render($request, Exception $e)
{
if ($e instanceof MethodNotAllowedHttpException) {
$errorResponse = [
'Message' => 'Error',
'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
];
return Response::json($errorResponse, 400);
}
if($e instanceof NotFoundHttpException)
{
$errorResponse = [
'Message' => 'Error',
'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
];
return Response::json($errorResponse, 400);
}
return parent::render($request, $e);
}
关于php - 带 Dingo 的 Laravel 5 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36370086/