I am getting a laravel error and I cannot figure out what is wrong with my code that would be causing the issue.
The issue is:
Symfony\Component\HttpKernel\Exception\NotFoundHttpException
…/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php148
If anyone needs more information please let me know and I will supply.
Edit: Here is the stack trace
#0 /home/action/workspace/ssbb/vendor/laravel/framework/src/Illuminate/Routing/Router.php(1049): Illuminate\Routing\RouteCollection->match(Object(Illuminate\Http\Request))
#1 /home/action/workspace/ssbb/vendor/laravel/framework/src/Illuminate/Routing/Router.php(1017): Illuminate\Routing\Router->findRoute(Object(Illuminate\Http\Request))
#2 /home/action/workspace/ssbb/vendor/laravel/framework/src/Illuminate/Routing/Router.php(996): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#3 /home/action/workspace/ssbb/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(776): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#4 /home/action/workspace/ssbb/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(746): Illuminate\Foundation\Application->dispatch(Object(Illuminate\Http\Request))
#5 /home/action/workspace/ssbb/vendor/laravel/framework/src/Illuminate/Session/Middleware.php(72): Illuminate\Foundation\Application->handle(Object(Illuminate\Http\Request), 1, true)
#6 /home/action/workspace/ssbb/vendor/laravel/framework/src/Illuminate/Cookie/Queue.php(47): Illuminate\Session\Middleware->handle(Object(Illuminate\Http\Request), 1, true)
#7 /home/action/workspace/ssbb/vendor/laravel/framework/src/Illuminate/Cookie/Guard.php(51): Illuminate\Cookie\Queue->handle(Object(Illuminate\Http\Request), 1, true)
#8 /home/action/workspace/ssbb/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Illuminate\Cookie\Guard->handle(Object(Illuminate\Http\Request), 1, true)
#9 /home/action/workspace/ssbb/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(642): Stack\StackedHttpKernel->handle(Object(Illuminate\Http\Request))
#10 /home/action/workspace/ssbb/public/index.php(49): Illuminate\Foundation\Application->run()
#11 {main} [] []
As I can't post in the comment section I am posting here
My friend you need to tell us which url you are trying to access,
As far as your route suggest it should be this in the browser localhost/laravel/-Your project name-/public/
As #jeemusu pointed out that this portion of your code is wrong
return View::make('site::index'), it should be ('site.index'),
There is a query constraint which accepts three parameters, you got only two there,
In this line
with('entry', Page::where('slug', 'welcome')->first()
please tell us what you are really trying to do
this was due to a URL not found so I just added the following code to my /app/start/global.php which then told me what URL it had trouble finding.
App::missing(function($e)
{
$url = Request::fullUrl();
Log::warning("404 for URL: $url");
return Response::make('404 not found', 404);
});
You can check everything using following code. Also filter 404 (NotFoundHttpException) error form your log file.
File : app/start/global.php
App::error(function(Exception $exception, $errorCode)
{
$requestUrl = Request::fullUrl();
$userAgent = Request::header('user-agent');
if($errorCode != 404){
Log::error('Exception', array(
'errorCode' => $errorCode,
'requestUrl' => $requestUrl,
'userAgent' => $userAgent,
'context' => $exception,
));
}
return Response::view('error-page-path.error-404', array(), 404);
// Here "error-404" is a blade view file in "error-page-path" directory
});
Related
I installed new Yii advanced framework. Nginx server.
Below url is working fine:
http://yii/backend/web/index.php?r=site/index
I created new CRUD using GII and accessed:
http://yii/backend/web/index.php?r=user/index
It showing below error:
An Error occurred while handling another error:
exception 'yii\web\ForbiddenHttpException' with message 'You are not allowed to perform this action.' in /private/var/www/yii/advanced/vendor/yiisoft/yii2/filters/AccessControl.php:151
Stack trace:
#0 /private/var/www/yii/advanced/vendor/yiisoft/yii2/filters/AccessControl.php(134): yii\filters\AccessControl->denyAccess(Object(yii\web\User))
#1 /private/var/www/yii/advanced/vendor/yiisoft/yii2/base/ActionFilter.php(71): yii\filters\AccessControl->beforeAction(Object(yii\web\ErrorAction))
#2 [internal function]: yii\base\ActionFilter->beforeFilter(Object(yii\base\ActionEvent))
#3 /private/var/www/yii/advanced/vendor/yiisoft/yii2/base/Component.php(541): call_user_func(Array, Object(yii\base\ActionEvent))
#4 /private/var/www/yii/advanced/vendor/yiisoft/yii2/base/Controller.php(263): yii\base\Component->trigger('beforeAction', Object(yii\base\ActionEvent))
#5 /private/var/www/yii/advanced/vendor/yiisoft/yii2/web/Controller.php(108): yii\base\Controller->beforeAction(Object(yii\web\ErrorAction))
#6 /private/var/www/yii/advanced/vendor/yiisoft/yii2/base/Controller.php(149): yii\web\Controller->beforeAction(Object(yii\web\ErrorAction))
#7 /private/var/www/yii/advanced/vendor/yiisoft/yii2/base/Module.php(455): yii\base\Controller->runAction('error', Array)
#8 /private/var/www/yii/advanced/vendor/yiisoft/yii2/web/ErrorHandler.php(85): yii\base\Module->runAction('site/error')
#9 /private/var/www/yii/advanced/vendor/yiisoft/yii2/base/ErrorHandler.php(109): yii\web\ErrorHandler->renderException(Object(yii\web\NotFoundHttpException))
#10 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\NotFoundHttpException))
#11 {main}
Previous exception:
exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "user/index".' in /private/var/www/yii/advanced/vendor/yiisoft/yii2/base/Module.php:461
Stack trace:
#0 /private/var/www/yii/advanced/vendor/yiisoft/yii2/web/Application.php(84): yii\base\Module->runAction('user/index', Array)
#1 /private/var/www/yii/advanced/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#2 /private/var/www/yii/advanced/backend/web/index.php(18): yii\base\Application->run()
#3 {main}
Next exception 'yii\web\NotFoundHttpException' with message 'Page not found.' in /private/var/www/yii/advanced/vendor/yiisoft/yii2/web/Application.php:96
Stack trace:
#0 /private/var/www/yii/advanced/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#1 /private/var/www/yii/advanced/backend/web/index.php(18): yii\base\Application->run()
#2 {main}
Did i missed any configuration?
Yii2 isset AccessControl
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'only' => ['create', 'update'],
'rules' => [
// deny all POST requests
[
'allow' => false,
'verbs' => ['POST']
],
// allow authenticated users
[
'allow' => true,
'roles' => ['#'],
],
// everything else is denied
],
],
];
}
exception 'yii\web\ForbiddenHttpException' with message 'You are not
allowed to perform this action.' in
/private/var/www/yii/advanced/vendor/yiisoft/yii2/filters/AccessControl.php:151
Here is yii2 code
/**
* Denies the access of the user.
* The default implementation will redirect the user to the login page if he is a guest;
* if the user is already logged, a 403 HTTP exception will be thrown.
* #param User $user the current user
* #throws ForbiddenHttpException if the user is already logged in.
*/
protected function denyAccess($user)
{
if ($user->getIsGuest()) {
$user->loginRequired();
} else {
throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
//this is 152 line
}
}
So I think its very clear that you need to login first, so go to http://yii/backend/web/index.php?r=user/login.
If dont have login user/login page then remove all behaviors section at the top of your UserController.
public function behaviors()
{
.
.
.
}
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
The docs say I can create a pool and any failed requests should call the "rejected" method, but instead I'm getting GuzzleHttp\Exception\ServerException. Here's my code:
$client = new GuzzleHttp\Client([
'base_uri' => ServerConfig::Json('file_server'),
]);
$requests = function() use ($client, $delete_time) {
foreach($this->pcs_master->pcs as $id => $pcs) {
$paths = $pcs->database->SelectSimpleArray('wopi_doc', 'wd_filepath', ['wd_deleted_at IS NOT NULL', 'wd_deleted_at < ?' => $delete_time]);
if ($paths) {
foreach (array_chunk($paths, self::WOPI_SOFT_DELETE_CHUNK_SIZE) as $chunk) {
yield $client->delete('/', [
'body' => json_encode(['paths' => $files]),
]);
}
}
}
};
$pool = new GuzzleHttp\Pool($client, $requests(), [
'concurrency' => self::WOPI_SOFT_DELETE_MAX_CONCURRENT_REQUESTS,
'fulfilled' => function ($response, $index) {
dump('fulfilled', $response, $index);
},
'rejected' => function ($reason, $index) {
dump('rejected', $reason, $index);
},
]);
$pool->promise()->wait();
Here's the exception:
TYPE: GuzzleHttp\Exception\ServerException
MESSAGE: Server error: 500
FILE: /path/to/my/project/vendor/guzzlehttp/guzzle/src/Middleware.php(68)
=== TRACE ===
#0 /path/to/my/project/vendor/guzzlehttp/promises/src/Promise.php(199): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))
#1 /path/to/my/project/vendor/guzzlehttp/promises/src/Promise.php(152): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array)
#2 /path/to/my/project/vendor/guzzlehttp/promises/src/TaskQueue.php(60): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise\{closure}()
#3 /path/to/my/project/vendor/guzzlehttp/promises/src/Promise.php(240): GuzzleHttp\Promise\TaskQueue->run(true)
#4 /path/to/my/project/vendor/guzzlehttp/promises/src/Promise.php(217): GuzzleHttp\Promise\Promise->invokeWaitFn()
#5 /path/to/my/project/vendor/guzzlehttp/promises/src/Promise.php(261): GuzzleHttp\Promise\Promise->waitIfPending()
#6 /path/to/my/project/vendor/guzzlehttp/promises/src/Promise.php(219): GuzzleHttp\Promise\Promise->invokeWaitList()
#7 /path/to/my/project/vendor/guzzlehttp/promises/src/Promise.php(62): GuzzleHttp\Promise\Promise->waitIfPending()
#8 /path/to/my/project/vendor/guzzlehttp/guzzle/src/Client.php(129): GuzzleHttp\Promise\Promise->wait()
#9 /path/to/my/project/vendor/guzzlehttp/guzzle/src/Client.php(87): GuzzleHttp\Client->request('delete', '/', Array)
#10 /path/to/my/project/class/crondaemon.php(5057): GuzzleHttp\Client->__call('delete', Array)
#11 /path/to/my/project/class/crondaemon.php(5057): GuzzleHttp\Client->delete('/', Array)
#12 /path/to/my/project/vendor/guzzlehttp/guzzle/src/Pool.php(55): CronDaemon::{closure}()
#13 [internal function]: GuzzleHttp\Pool::GuzzleHttp\{closure}()
#14 /path/to/my/project/vendor/guzzlehttp/promises/src/EachPromise.php(73): Generator->rewind()
#15 /path/to/my/project/vendor/guzzlehttp/guzzle/src/Pool.php(74): GuzzleHttp\Promise\EachPromise->promise()
#16 /path/to/my/project/class/crondaemon.php(5073): GuzzleHttp\Pool->promise()
#17 [internal function]: CronDaemon->DeleteWopiDocs()
#18 /path/to/my/project/tests/cron.php(46): call_user_func(Array)
#19 /path/to/my/project/tests/cron.php(51): CronDaemonTestScript::main(Array)
#20 {main}
It looks like the exception is being thrown on the $client->delete line, but I thought that was supposed to create a Request object but not send it yet (that's the job of the pool)?
client::get(), client::put(), client::post(), client::delete() are abstractions for client::request() which in itself is an abstraction for client::requestAsync().You are attempting to yield a ResponseInterface instance.
If you are going to use GuzzleHttp\Pool, you will have to manually create the Psr\http-message\Request objects.
yield new GuzzleHttp\Psr7\Request($method, $uri, $headers_array, $body, $protocol_version);
Further information can be obtained by checking out concurrent requests and GuzzleHttp\Psr7\Request
Edit: Response to question in comments.
Ultimately, each request you want to have sent, is sent using Client::sendAsync(). This means that any option previously configured within the Client will remain valid while it is being used within the pool.
It appears that I have to wrap the Promise in a function for some reason:
foreach (array_chunk($paths, self::WOPI_SOFT_DELETE_CHUNK_SIZE) as $chunk) {
yield function() use ($client, $files) {
return $client->deleteAsync('/', [
'body' => json_encode(['paths' => $files]),
]);
};
}
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 setting up a custom Acl for a Laravel 4.1 application.
My Routes.php file applies a before filter:
// Global authenticator
Route::filter('auth.vle', function()
{
return (new vleAuth)->authenticate();
});
// Authenticate all requests, except those to /login, /logout and /forgottenpassword
Route::whenRegex('/^(?!login|logout)(.*)$/', 'auth.vle');
and my vleAuth authenticate() method:
public function authenticate()
{
$this->acl = new vleAclService();
$endpoint = Route::current()->getAction()['controller'];
if (!$this->acl->validateEndpoint($endpoint)) {
Log::info('Routing', array( Route::current()->getUri(), $endpoint));
App::abort(403, 'Unauthorized action.');
}
}
When I access an endpoint which I am privileged to access, no problems; and when I access an endpoint that I'm not privileged to access, then I get a Forbidden - We're really sorry but you don't have the necessary permissions to access this page. message, so the authentication is working correctly as far as the "front-end" is concerned, and the routing information in the log bears this out.
However, whenever I try to access an endpoint that I'm not authenticated for, I also get a stack trace dumped in the Laravel log
[2014-06-12 15:00:16] production.INFO: ROUTE VALIDATION ["View_Reviews_ReviewsController#getIndex",false] []
[2014-06-12 15:00:16] production.ERROR: exception 'Symfony\Component\HttpKernel\Exception\HttpException' with message 'Unauthorized action.' in /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:875
Stack trace:
#0 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(211): Illuminate\Foundation\Application->abort(403, 'Unauthorized ac...')
#1 /srv/api/laravel/app/controllers/vleAuth.php(104): Illuminate\Support\Facades\Facade::__callStatic('abort', Array)
#2 /srv/api/laravel/app/controllers/vleAuth.php(104): Illuminate\Support\Facades\App::abort(403, 'Unauthorized ac...')
#3 /srv/api/laravel/app/routes.php(20): vleAuth->authenticate()
#4 [internal function]: {closure}(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#5 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(199): call_user_func_array(Object(Closure), Array)
#6 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(154): Illuminate\Events\Dispatcher->fire('router.filter: ...', Array, true)
#7 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(1399): Illuminate\Events\Dispatcher->until('router.filter: ...', Array)
#8 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(1262): Illuminate\Routing\Router->callRouteFilter('auth.vle', Array, Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#9 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(1246): Illuminate\Routing\Router->callPatternFilters(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#10 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(996): Illuminate\Routing\Router->callRouteBefore(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#11 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(968): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#12 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(738): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#13 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(708): Illuminate\Foundation\Application->dispatch(Object(Illuminate\Http\Request))
#14 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Http/FrameGuard.php(38): Illuminate\Foundation\Application->handle(Object(Illuminate\Http\Request), 1, true)
#15 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Session/Middleware.php(72): Illuminate\Http\FrameGuard->handle(Object(Illuminate\Http\Request), 1, true)
#16 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Cookie/Queue.php(47): Illuminate\Session\Middleware->handle(Object(Illuminate\Http\Request), 1, true)
#17 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Cookie/Guard.php(51): Illuminate\Cookie\Queue->handle(Object(Illuminate\Http\Request), 1, true)
#18 /home/vagrant/vleAppV2/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Illuminate\Cookie\Guard->handle(Object(Illuminate\Http\Request), 1, true)
#19 /home/vagrant/vleAppV2/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(606): Stack\StackedHttpKernel->handle(Object(Illuminate\Http\Request))
#20 /home/vagrant/vleAppV2/public/index.php(49): Illuminate\Foundation\Application->run()
#21 {main} [] []
I'm trying to suppress this because I don't want the logs filling up with stack traces; just the log info that I'm recording myself is all I actually need in the logs.
I've tried suppressing it by registering a new error handling function in app/global.php:
App::error(function(Exception $exception, $code)
{
// Don't log 403s
if ($exception instanceof Symfony\Component\HttpKernel\Exception\HttpException) {
return;
}
Log::error($exception);
});
but this doesn't seem to have any effect at all.
I've also tried wrapping the App:abort() in vleAuth.authenticate() within a try/catch block, but the Exception appears to have already been handled before this catch, so it hasn't helped either.
I've rerun composer dump-autoload to rebuild all appropriate autoloading, and have restarted the server just in case old scripts are being help in OpCache.
Can anybody tell me how I should be suppressing this stack trace?
The solution was in returning a response from the custom error handling function rather than a null return
App::error(function(Exception $exception, $code)
{
// Don't log 403s
if ($exception instanceof Symfony\Component\HttpKernel\Exception\HttpException) {
return Response::view('errors.403', array(), 403);
}
Log::error($exception);
});
This still displays the 403 page correctly, but overrides calling the default error handler that was generating the stack trace