I've taken the Doctrine 2 and ZF2 installation, with pagination, and tried to apply a search function to the method.
The album list is accessible via the usual route http://myapp/album
My current code appears to build a usable query using doctrine's createQueryBuilder()
When I give no parameters to title/artist then the result of $qb->getDql(); is SELECT a FROM Album\Entity\Album a and it returns no error and paginated results fine.
My method;
public function indexAction()
{
$view = new ViewModel();
$repository = $this->getEntityManager()->getRepository('Album\Entity\Album');
$qb = $repository->createQueryBuilder('album');
$qb->add('select', 'a')
->add('from', 'Album\Entity\Album a');
if ($this->params()->fromQuery('title')) {
$qb->add('where','title like :title');
$qb->setParameter(':title', '%' . $this->params()->fromQuery('title') . '%');
}
if ($this->params()->fromQuery('artist')) {
$qb->add('where','artist like :artist');
$qb->setParameter(':artist', '%' . $this->params()->fromQuery('artist') . '%');
}
$q = $qb->getDql();
$paginator = new Paginator(new DoctrineAdapter(new ORMPaginator($this->getEntityManager()->createQuery($q))));
$paginator->setDefaultItemCountPerPage(10);
$page = (int)$this->params()->fromQuery('page');
if ($page) $paginator->setCurrentPageNumber($page);
$view->setVariable('paginator', $paginator);
return $view;
}
But when I pass a query through the URL http://myapp/album?title=In%20My%20Dreams the result of $qb->getDql(); is SELECT a FROM Album\Entity\Album a WHERE title like :title which returns the error below.
Zend\Paginator\Exception\RuntimeException
File:
/Users/luke/Sites/hotelio/vendor/zendframework/zendframework/library/Zend/Paginator/Paginator.php:637
Message:
Error producing an iterator
Stack trace:
#0 /myapp/module/Album/view/album/album/index.phtml(20): Zend\Paginator\Paginator->getIterator()
#1 /myapp/vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php(507): include('/myapp...')
#2 /myapp/vendor/zendframework/zendframework/library/Zend/View/View.php(205): Zend\View\Renderer\PhpRenderer->render(Object(Zend\View\Model\ViewModel))
#3 /myapp/vendor/zendframework/zendframework/library/Zend/View/View.php(233): Zend\View\View->render(Object(Zend\View\Model\ViewModel))
#4 /myapp/vendor/zendframework/zendframework/library/Zend/View/View.php(198): Zend\View\View->renderChildren(Object(Zend\View\Model\ViewModel))
#5 /myapp/vendor/zendframework/zendframework/library/Zend/Mvc/View/Http/DefaultRenderingStrategy.php(102): Zend\View\View->render(Object(Zend\View\Model\ViewModel))
#6 [internal function]: Zend\Mvc\View\Http\DefaultRenderingStrategy->render(Object(Zend\Mvc\MvcEvent))
#7 /myapp/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#8 /myapp/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('render', Object(Zend\Mvc\MvcEvent), Array)
#9 /myapp/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php(347): Zend\EventManager\EventManager->trigger('render', Object(Zend\Mvc\MvcEvent))
#10 /myapp/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php(322): Zend\Mvc\Application->completeRequest(Object(Zend\Mvc\MvcEvent))
#11 /myapp/public/index.php(12): Zend\Mvc\Application->run()
#12 {main}
I understand that the error is where the view is accessing the variable, but as the paginator handles the modified query it appears to get as far of the view before erroring. I am not really sure what is going on here.
For the avoidance of doubt, the original method which also operates without error;
public function indexAction()
{
$view = new ViewModel();
$repository = $this->getEntityManager()->getRepository('Album\Entity\Album');
$paginator = new Paginator(new DoctrineAdapter(new ORMPaginator($this->getEntityManager()->createQuery($repository->createQueryBuilder('album')))));
$paginator->setDefaultItemCountPerPage(10);
$page = (int)$this->params()->fromQuery('page');
if ($page) $paginator->setCurrentPageNumber($page);
$view->setVariable('paginator', $paginator);
return $view;
}
I was getting the same error. In my case the problem was "date.timezone" not being set in php.ini. This was causing the following code to actually catch a \DateTime() exception.
Zend\Paginator\Paginator
public function getIterator()
{
try {
return $this->getCurrentItems();
} catch (\Exception $e) {
throw new Exception\RuntimeException('Error producing an iterator', null, $e);
}
}
Apart from bad DQL, "error producing an iterator" can also occur when data/DoctrineORMModule/Proxy does not have the correct write permissions set on it:
chmod 755 data/DoctrineORMModule/Proxy
Related
php7.0, Phalcon 3.2, MongoDB 3.2.14
I want to connect to MongoDB, but in Phalcon documentation only about connection via MongoClient() and working with it. I have php7.0 and MongoClient() is deprecated in it. How I can correctly use \MongoDB\Driver\Manager() with Phalcon?
In services.php I wrote this:
/**
* MongoDB connection
*/
$di->set( "mongo", function () {
$config = $this->getConfig();
$db_string = sprintf( 'mongodb://%s:%s/%s', $config->mongodb->host, $config->mongodb->port, $config->mongodb->database );
if( isset( $config->mongodb->user ) AND isset( $config->mongodb->password ) ) {
$db_string = sprintf( 'mongodb://%s:%s#%s:%s/%s',
$config->mongodb->user,
(string)$config->mongodb->password,
$config->mongodb->host,
(string)$config->mongodb->port,
$config->mongodb->database );
}
try {
return new \MongoDB\Driver\Manager( $db_string );
} catch (MongoConnectionException $e) {
die( 'Failed to connect to MongoDB '.$e->getMessage() );
}
},
true
);
It works. But in models there are errors. In app/models/User.php I wrote:
use Phalcon\Mvc\Collection;
class User extends Collection
{
public function initialize()
{
$this->setSource('users');
}
}
And in controller:
class IndexController extends ControllerBase
{
public function indexAction()
{
echo User::count();
}
}
In browser I have this:
Call to undefined method ::selectcollection()
#0 [internal function]: Phalcon\Mvc\Collection::_getGroupResultset(Array, Object(User), Object(MongoDB\Driver\Manager))
#1 /var/www/testing/app/controllers/IndexController.php(8): Phalcon\Mvc\Collection::count()
#2 [internal function]: IndexController->indexAction()
#3 [internal function]: Phalcon\Dispatcher->callActionMethod(Object(IndexController), 'indexAction', Array)
#4 [internal function]: Phalcon\Dispatcher->_dispatch()
#5 [internal function]: Phalcon\Dispatcher->dispatch()
#6 /var/www/testing/public/index.php(42): Phalcon\Mvc\Application->handle()
#7 {main}
How I can do it correclty? :) sorry for my English, I from Russia :)
My original question is here.
Use Incubator package: https://github.com/phalcon/incubator
See example of using here -
https://github.com/phalcon/incubator/tree/master/Library/Phalcon/Db/Adapter#mongodbclient
Getting an error when trying to list the groups of my domain through the PHP Directory API. The really weird thing is that if I list the groups using OAuth playground, it works seamlessly with these scopes:
https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.group.member
Note: I'm not using a service account do this. My email address has super admin access, so I'm assuming this should be fine when trying to manage groups and group members? I'm using Slim 3 to handle the applications details. My client is initialized and authenticated (according to a quick var_dump on the object), yet I get an error when trying to do:
$service = new \Google_Service_Directory($this->client);
var_dump($service->groups->listGroups(["domain" => "example.google.com"])); // placeholder domain for SO
and here is the error I'm receiving when trying to load the page so I can list the groups:
#0 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Http/REST.php(62): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request), Object(Google_Client))
#1 [internal function]: Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request))
#2 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Task/Runner.php(174): call_user_func_array(Array, Array)
#3 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Http/REST.php(46): Google_Task_Runner->run()
#4 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Client.php(593): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#5 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Service/Resource.php(240): Google_Client->execute(Object(Google_Http_Request))
#6 /Applications/MAMP/htdocs/aslists/vendor/google/apiclient/src/Google/Service/Directory.php(2122): Google_Service_Resource->call('list', Array, 'Google_Service_...')
#7 /Applications/MAMP/htdocs/aslists/src/controllers/DashboardController.php(23): Google_Service_Directory_Groups_Resource->listGroups(Array)
#8 [internal function]: a_s\controllers\DashboardController->index(Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
...
#18 {main}
Why would the query fail using the PHP API, but succeed on OAuth playground?
Update 1
My apologies in advance, this will contain a lot of code...
I spent some time tinkering around following the PHP Quickstart example where my client_secret.json file is loaded into the application like so:
$this->client->setAuthConfigFile('/path/to/client_secret.json');
$credentialsPath = $this->expandHomeDirectory('/path/to/.credentials/admin-directory_v1-php-quickstart.json');
if(file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
}
if(isset($accessToken)) {
$this->client->setAccessToken($accessToken);
}
if($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($this->client->getRefreshToken());
file_put_contents($credentialsPath, $this->client->getAccessToken());
}
$this->service = new \Google_Service_Directory($this->client);
If I use this method, it works perfectly with my application – very strange. I did additional investigation between this method and using Google to sign into the application and I was unable to find anything conclusive. Given that, it should work if I use Google to sign in, but it still doesn't.
Here is how I am initializing the client:
class GoogleController extends Controller {
private static $APP_NAME = "Lists Manager";
private static $CLIENT_ID = "...";
private static $CLIENT_SECRET = "...";
private static $REDIRECT_URI = "postmessage";
private static $ACCESS_TYPE = "offline";
private static $scopes = [
\Google_Service_Oauth2::USERINFO_PROFILE,
\Google_Service_Oauth2::USERINFO_EMAIL,
\Google_Service_Directory::ADMIN_DIRECTORY_GROUP,
\Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER,
\Google_Service_Directory::ADMIN_DIRECTORY_USER
];
protected $client;
public function __construct($container) {
parent::__construct($container);
$this->client = new \Google_Client();
$this->client->setApplicationName(self::$APP_NAME);
$this->client->setClientId(self::$CLIENT_ID);
$this->client->setClientSecret(self::$CLIENT_SECRET);
$this->client->setRedirectUri(self::$REDIRECT_URI);
$this->client->setScopes(self::$scopes);
$this->client->setAccessType(self::$ACCESS_TYPE);
}
}
From here, I have another controller which extends GoogleController that contains an ajax endpoint (i.e. where the access code it POSTed to). The code for this is shown below:
class LoginController extends GoogleController {
public function __construct($container) {
parent::__construct($container);
}
public function login($request, $response) {
if($this->client->isAccessTokenExpired()) {
unset($_SESSION[GoogleController::AS_PERSISTENT_CLIENT_OBJECT]);
$this->tokens = $this->client->authenticate($request->getBody()->getContents());
// $this->client->setAccessToken($this->token); // Not sure if I need to do this. Either way, I still get the exception
}
$_SESSION[GoogleController::AS_PERSISTENT_CLIENT_OBJECT] = serialize($this->client);
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write($this->generateJsonSuccess('dashboard'));
}
}
I have checked the official repo of monolog and put together below code, its working great and I am getting response in Slack. But the response are very verbose, How Can i get simple response, without Stack Trace.
And as suggested on doc I have added $monolog->pushProcessor(new WebProcessor($_SERVER)); but its not giving any information about requested URL and server.
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
if ($this->app->environment('production')) {
// Get The Logger
$monolog = Log::getMonolog();
// **********************************************************************************************
// I have tried official WebProcessor to get url, but its not giving me anything
// **********************************************************************************************
$monolog->pushProcessor(new WebProcessor($_SERVER));
$monolog->pushProcessor(function ($record) {
$record['extra']['session_id'] = Cookie::get(config('session.cookie'));
$record['extra']['request_id'] = Session::get('request_id');
return $record;
});
$slackHandler = new SlackHandler(env('SLACK_TOKEN'), '#sss-sslogs', 'sss-log', true, ':warning:', Logger::ERROR);
// **********************************************************************************************
// Setup Line Formatter but no luck
// **********************************************************************************************
// the default date format is "Y-m-d H:i:s"
$dateFormat = "Y n j, g:i a";
// the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
$output = "%datetime% > %level_name% > %message% %context% %extra%\n";
// finally, create a formatter
$formatter = new LineFormatter($output, $dateFormat);
$slackHandler->setFormatter($formatter);
$monolog->pushHandler($slackHandler);
}
}
Above code is giving me below response in Slack channel
exception 'Illuminate\Database\Eloquent\ModelNotFoundException' with message 'No query results for model [App\User].' in /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:151
Stack trace:
#0 /home/vagrant/Code/App/app/Http/Controllers/PortfolioController.php(30): Illuminate\Database\Eloquent\Builder->firstOrFail()
#1 [internal function]: App\Http\Controllers\PorofileController->show('users')
#2 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(246): call_user_func_array(Array, Array)
#3 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(162): Illuminate\Routing\Controller->callAction('show', Array)
#4 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(107): Illuminate\Routing\ControllerDispatcher->call(Object(App\Http\Controllers\PortfolioController), Object(Illuminate\Routing\Route), 'show')
#5 [internal function]: Illuminate\Routing\ControllerDispatcher->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#6 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#7 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#8 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(101): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#9 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(108): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#10 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(67): Illuminate\Routing\ControllerDispatcher->callWithinStack(Object(App\Http\Controllers\PortfolioController), Object(I…
Level
----------------
ERROR
Where is the requested URL and session data??
How can I get only below part with requested URL, I am not interested in Stack trace:
exception 'Illuminate\Database\Eloquent\ModelNotFoundException' with message 'No query results for model [App\User].' in /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:151
In my routes.php, I have this:
$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:
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 {
//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
Second Attempted Solution:
From Dingo's Returning Errors, docs, I tested what would happen if I returned one of the exceptions:
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:
[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()
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.
Customer::findOrFail($id);
then you could catch all of this type exception in app/start/global.php like this.
App::error(function(ModelNotFoundException $modelNotFoundException){
$errorResponse = [
'errors' => 'Not found any resource',
'message' => $modelNotFoundException->getMessage()
];
return Response::json($errorResponse, 404); //404 = Not found
});
Reading from Dingo's Returning Errors docs, it says:
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
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
So in short, you need to throw one of the exceptions above that Dingo supports back to Dingo. For example:
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.
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.
I'm trying to use Zend Db findBy() magic method, but it gives me this error:
Application error
Exception information:
Message: File "Game.php" does not exist or class "Game" was not found in the file
Stack trace:
#0 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Db\Table\Row\Abstract.php(872): Zend_Db_Table_Row_Abstract->_getTableFromString('Game')
#1 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Db\Table\Row\Abstract.php(1154): Zend_Db_Table_Row_Abstract->findDependentRowset('Game', NULL, NULL)
#2 C:\Zend\Apache2\htdocs\dev.gamenomad.com\application\controllers\GameController.php(125): Zend_Db_Table_Row_Abstract->__call('findGame', Array)
#3 C:\Zend\Apache2\htdocs\dev.gamenomad.com\application\controllers\GameController.php(125): Zend_Db_Table_Row->findGame()
#4 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Controller\Action.php(516): GameController->platformAction()
#5 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Controller\Dispatcher\Standard.php(295): Zend_Controller_Action->dispatch('platformAction')
#6 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#7 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#8 C:\Zend\ZendServer\share\ZendFramework\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#9 C:\Zend\Apache2\htdocs\dev.gamenomad.com\public\index.php(26): Zend_Application->run()
#10 {main}
Request Parameters:
array (
'controller' => 'game',
'action' => 'platform',
'x' => '2',
'module' => 'default',
)
Seems like it doesn't detect Game.php even though it exists inside /application/models/DbTable/Game.php
Are there any rules or exceptions I am missing?
This is my code
public function platformAction()
{
// action body
$platform = intval($this->_request->getParam('x'));
$platformTable = new Application_Model_DbTable_Platform();
$xbox360 = $platformTable->find($platform)->current();
//$games = $xbox360->findDependentRowset('Application_Model_DbTable_Game');
$games = $xbox360->findGame();
if(isset($games))
{
if(count($games)>0)
{
foreach($games as $game)
{
echo "{$game->name}<br />";
}
}
}
}