Laravel Dingo Api - 如何从 API 控制器返回 JSON 格式的错误响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24560351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Dingo Api - How to return JSON formatted error response from API Controller?
提问by Muserk
In my routes.php, I have this:
在我的 routes.php 中,我有这个:
$apiSettings = [
'version' => 'v1',
'prefix' => 'api',
'protected' => true
];
Route::api($apiSettings, function() {
Route::get('venue', 'ApiDataController@venue');
});
The protected venue API route accesses a controller method. The controller method performs the Eloquent Query on a Venues model, and returns the response. This works perfectly. The issue is in if I want to return an error - I am unsure how to. Here is the Venue Method:
受保护的场地 API 路由访问控制器方法。控制器方法在 Venues 模型上执行 Eloquent Query,并返回响应。这完美地工作。问题在于我是否想返回错误 - 我不确定如何返回。这是场地方法:
public function venue(){
try {
//Some code that returns an exception
} catch(someexception $e) {
//How do I return the exception such that Dingo will parse it into a proper JSON response?
}
$response = Venue::with('address')->get();
return $response;
}
My attempted solution (in the try block):
我尝试的解决方案(在 try 块中):
try {
//some code that returns an exception
} catch(someexception $e) {
$response = array(
'message' => 'some random exception message'
);
return Response::json($response, 403);
}
I got the following error when I attempted to do that:
Argument 1 passed to Dingo\Api\Http\Response::makeFromExisting() must be an instance of Illuminate\Http\Response, instance of Illuminate\Http\JsonResponse given, called in /vagrant/www/planat-app/vendor/dingo/api/src/Routing/Router.php on line 165 and defined
当我尝试这样做时出现以下错误:
Argument 1 passed to Dingo\Api\Http\Response::makeFromExisting() must be an instance of Illuminate\Http\Response, instance of Illuminate\Http\JsonResponse given, called in /vagrant/www/planat-app/vendor/dingo/api/src/Routing/Router.php on line 165 and defined
Second Attempted Solution: From Dingo's Returning Errors, docs, I tested what would happen if I returned one of the exceptions:
第二次尝试的解决方案:从 Dingo 的返回错误文档中,我测试了如果返回异常之一会发生什么:
public function venue(){
throw new Symfony\Component\HttpKernel\Exception\ConflictHttpException('err);
}
However, instead of returning the error as a JSON response, a laravel error page comes up, with the following error displayed:
但是,不是将错误作为 JSON 响应返回,而是出现一个 Laravel 错误页面,并显示以下错误:
[internal function]: ApiDataController->venue() #1 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(231): call_user_func_array(Array, Array) #2 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(93): Illuminate\Routing\Controller->callAction('venue', Array) #3 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(62): Illuminate\Routing\ControllerDispatcher->call(Object(ApiDataController), Object(Illuminate\Routing\Route), 'venue') #4 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(930): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(Dingo\Api\Http\InternalRequest), 'ApiDataControll...', 'venue') #5 [internal function]: Illuminate\Routing\Router->Illuminate\Routing\{closure}() #6 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/Route.php(105): call_user_func_array(Object(Closure), Array) #7 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(996): Illuminate\Routing\Route->run(Object(Dingo\Api\Http\InternalRequest)) #8 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(964): Illuminate\Routing\Router->dispatchToRoute(Object(Dingo\Api\Http\InternalRequest)) #9 /vagrant/www/planat-app/vendor/dingo/api/src/Routing/Router.php(147): Illuminate\Routing\Router->dispatch(Object(Dingo\Api\Http\InternalRequest)) #10 /vagrant/www/planat-app/vendor/dingo/api/src/Dispatcher.php(337): Dingo\Api\Routing\Router->dispatch(Object(Dingo\Api\Http\InternalRequest)) #11 /vagrant/www/planat-app/vendor/dingo/api/src/Dispatcher.php(278): Dingo\Api\Dispatcher->dispatch(Object(Dingo\Api\Http\InternalRequest)) #12 /vagrant/www/planat-app/vendor/dingo/api/src/Dispatcher.php(213): Dingo\Api\Dispatcher->queueRequest('get', 'venue', Array) #13 /vagrant/www/planat-app/app/routes.php(51): Dingo\Api\Dispatcher->get('venue') #14 [internal function]: {closure}() #15 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/Route.php(105): call_user_func_array(Object(Closure), Array) #16 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(996): Illuminate\Routing\Route->run(Object(Illuminate\Http\Request)) #17 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(964): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request)) #18 /vagrant/www/planat-app/vendor/dingo/api/src/Routing/Router.php(147): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request)) #19 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(738): Dingo\Api\Routing\Router->dispatch(Object(Illuminate\Http\Request)) #20 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(708): Illuminate\Foundation\Application->dispatch(Object(Illuminate\Http\Request)) #21 /vagrant/www/planat-app/vendor/dingo/api/src/Http/Middleware/RateLimit.php(97): Illuminate\Foundation\Application->handle(Object(Illuminate\Http\Request), 1, true) #22 /vagrant/www/planat-app/vendor/dingo/api/src/Http/Middleware/Authentication.php(102): Dingo\Api\Http\Middleware\RateLimit->handle(Object(Illuminate\Http\Request), 1, true) #23 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Session/Middleware.php(72): Dingo\Api\Http\Middleware\Authentication->handle(Object(Illuminate\Http\Request), 1, true) #24 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Cookie/Queue.php(47): Illuminate\Session\Middleware->handle(Object(Illuminate\Http\Request), 1, true) #25 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Cookie/Guard.php(51): Illuminate\Cookie\Queue->handle(Object(Illuminate\Http\Request), 1, true) #26 /vagrant/www/planat-app/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Illuminate\Cookie\Guard->handle(Object(Illuminate\Http\Request), 1, true) #27 /vagrant/www/planat-app/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(606): Stack\StackedHttpKernel->handle(Object(Illuminate\Http\Request)) #28 /vagrant/www/planat-app/public/index.php(49): Illuminate\Foundation\Application->run()
回答by Nuruzzaman Milon
As you are building api, you can catch similar types of exception globally. For example, if a user tried to get a customer with an ID which doesn't exists, then you could do this.
在构建 api 时,您可以全局捕获类似类型的异常。例如,如果用户尝试使用不存在的 ID 获取客户,那么您可以执行此操作。
Customer::findOrFail($id);
then you could catch all of this type exception in app/start/global.php
like this.
那么你可以app/start/global.php
像这样捕获所有这种类型的异常。
App::error(function(ModelNotFoundException $modelNotFoundException){
$errorResponse = [
'errors' => 'Not found any resource',
'message' => $modelNotFoundException->getMessage()
];
return Response::json($errorResponse, 404); //404 = Not found
});
回答by Unnawut
Reading from Dingo's Returning Errorsdocs, it says:
阅读 Dingo 的返回错误文档,它说:
Instead of manually creating and returning an error response you can simply throw an exception and the package will handle the exception and return an appropriate response.
The following is a list of all the supported exceptions that you should throw when you encounter an error.
Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException Symfony\Component\HttpKernel\Exception\BadRequestHttpException Symfony\Component\HttpKernel\Exception\ConflictHttpException Symfony\Component\HttpKernel\Exception\GoneHttpException Symfony\Component\HttpKernel\Exception\HttpException Symfony\Component\HttpKernel\Exception\LengthRequiredHttpException Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException Symfony\Component\HttpKernel\Exception\NotFoundHttpException Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException
您可以简单地抛出异常,而不是手动创建和返回错误响应,包将处理异常并返回适当的响应。
以下是遇到错误时应抛出的所有受支持异常的列表。
Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException Symfony\Component\HttpKernel\Exception\BadRequestHttpException Symfony\Component\HttpKernel\Exception\ConflictHttpException Symfony\Component\HttpKernel\Exception\GoneHttpException Symfony\Component\HttpKernel\Exception\HttpException HttpKernel\ \Exception\LengthRequiredHttpException Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException Symfony\Component\HttpKernel\Exception\NotFoundHttpException Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException Symfony\HttpKernel\Exception\NotAcceptableHttpException \Component\HttpKernel\Exception\ServiceUnavailableHttpExceptionSymfony\Component\HttpKernel\Exception\TooManyRequestsHttpException Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException
It also supports some generic resource exceptions that you can pass validation errors onto as well:
它还支持一些通用资源异常,您也可以将验证错误传递给这些异常:
Dingo\Api\Exception\DeleteResourceFailedException Dingo\Api\Exception\ResourceException Dingo\Api\Exception\StoreResourceFailedException Dingo\Api\Exception\UpdateResourceFailedException
Dingo\Api\Exception\DeleteResourceFailedException Dingo\Api\Exception\ResourceException Dingo\Api\Exception\StoreResourceFailedException Dingo\Api\Exception\UpdateResourceFailedException
So in short, you need to throw one of the exceptions above that Dingo supports back to Dingo. For example:
所以简而言之,您需要将 Dingo 支持的上述异常之一抛回 Dingo。例如:
try {
//Some code that returns an exception
} catch(SomeException $e) {
throw new Symfony\Component\HttpKernel\Exception\HttpException($e->getMessage);
}
Or in fact, if the exception thrown is one of the type above, or one that extends them, you can just remove your try/catch clause completely. The exception should be automatically thrown back to Dingo to handle it.
或者事实上,如果抛出的异常是上述类型之一,或者是扩展它们的类型,您可以完全删除 try/catch 子句。异常应该被自动抛出回 Dingo 来处理它。
回答by Avinash Singh Rathi
Please check this:
请检查这个:
try {
//some code that returns an exception
} catch(\Exception $e) {
$response = array(
'message' => 'some random exception message'
);
return response()->json($response, 403);
}
Please check and let me know.
请检查并让我知道。