Predis \ Connection \ ConnectionException Laravel 4 - laravel-4

When I try to execute my project I've got this exception :
Predis \ Connection \ ConnectionException
open: C:\wamp\www\laravel-pagination\vendor\predis\predis\lib\Predis\Connection\AbstractConnection.php
* Helper method to handle connection errors.
*
* #param string $message Error message.
* #param int $code Error code.
*/
protected function onConnectionError($message, $code = null)
{
CommunicationException::handle(new ConnectionException($this, "$message [{$this->parameters->scheme}://{$this->getIdentifier()}]", $code));
}
Can anyone help me to solve my problem ?

If you're not using Redis, you can change 'driver' => 'redis' to 'driver' => 'file' in your app/config/cache.php file as well as your app/config/session.php file.

Is not an elegant solution but you can catch the exception, so in your public/index.php try:
try{
$app->run();
} catch (\Predis\Connection\ConnectionException $ex) {
}
and in the catch restart your app after had something useful.

Related

Unable to retrieve the file_size for file when using Storage::fake for testing

I just upgraded my app from Laravel v8 to v9. Now I'm having an issue with the following code throwing this error:
League\Flysystem\UnableToRetrieveMetadata : Unable to retrieve the file_size for file at location: test_file.xlsx.
My controller:
<?php
namespace App\Http\Controllers\Reports;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
class ReportDownloadController extends Controller
{
/**
* Handle the incoming request.
*
* #param string $path
* #return \Symfony\Component\HttpFoundation\StreamedResponse
*/
public function __invoke(string $path): \Symfony\Component\HttpFoundation\StreamedResponse
{
return Storage::disk('temp')->download($path, request()->query('filename'));
}
}
The relevant test:
/** #test */
public function it_returns_a_file_download_with_the_provided_filename_presented_to_the_user()
{
$this->withoutExceptionHandling();
Storage::fake('temp');
$fakeFile = UploadedFile::fake()->create('test_file.xlsx');
Storage::disk('temp')->put('test_file.xlsx', $fakeFile);
$response = $this->actingAs($this->user)
->getJson(route('reports.download', ['path' => 'test_file.xlsx', 'filename' => 'Appropriate.xlsx']));
$response->assertDownload('Appropriate.xlsx');
}
I know Flysystem was updated to v3, but I can't seem to figure out how to resolve this issue.
I even created an empty Laravel 9 app to test with the following code and still get the same error, so I don't think it is my app.
public function test_that_file_size_can_be_retrieved()
{
Storage::fake('local');
$fakeFile = UploadedFile::fake()->create('test_file.xlsx', 10);
Storage::disk('local')->put('test_file.xlsx', $fakeFile);
$this->assertEquals(10, (Storage::disk('local')->size('test_file.xlsx') / 1024));
}
What am is missing?
I've had the same problem when switching from Laravel 8 to Laravel 9.
The error Unable to retrieve the file_size was actually thrown because it couldn't find the file at all at the path provided.
In my case, it turned out that the path that was provided to the download function started with a /, which wasn't cause for problem with Flysystem 2 but apparently is with Flysystem 3.
Given the tests you're showing it doesn't look like it's the issue here but maybe this will help anyway.
So it turns out my test was broken all along. I should have been using $fakeFile->hashName() and I had the filename where I should have had '/' for the path in my Storage::put().
Here are the corrected tests that pass as expected:
/** #test */
public function it_returns_a_file_download_with_the_provided_filename_presented_to_the_user()
{
$this->withoutExceptionHandling();
Storage::fake('temp');
$fakeFile = UploadedFile::fake()->create('test_file.xlsx');
Storage::disk('temp')->put('/', $fakeFile);
$response = $this->actingAs($this->user)
->getJson(route('reports.download', ['path' => $fakeFile->hashName(), 'filename' => 'Appropriate.xlsx']));
$response->assertDownload('Appropriate.xlsx');
}
and
public function test_that_file_size_can_be_retrieved()
{
Storage::fake('local');
$fakeFile = UploadedFile::fake()->create('test_file.xlsx');
Storage::disk('local')->put('/', $fakeFile);
$this->assertEquals(0, Storage::disk('local')->size($fakeFile->hashName()));
}
Thanks, #yellaw. Your comment about it not being able to find the file at the path provided helped me realize I had done something stupid.

Call to undefined method Symfony\Component\HttpFoundation\Response::create() when adding webhook in facebook

BotMan Version: 2.6.1
PHP Version: 8.1
Messaging Service(s): Facebook
Cache Driver: LaravelCache
Laravel: 9.18
Description:
Hi, im geting this error in laravel 9, how to handle it easiest way?
method create not exist, so should i make new class that extends Request with method create ?
I already tried to change all references from use Symfony\Component\HttpFoundation\Response;
to Illuminate\Http\Response (and Request) but this also not work.
curl -X GET "https://somedomain.org/botman?hub.verify_token=MySecretTokenFromDotENV&hub.challenge=CHALLENGE_ACCEPTED&hub.mode=subscribe"
Reponse:
Error: Call to undefined method Symfony\Component\HttpFoundation\Response::create() in file /var/www/nams/botman/driver-facebook/src/FacebookDriver.php on line 120
#0 /var/www/nams/botman/botman/src/Drivers/DriverManager.php(157): BotMan\Drivers\Facebook\FacebookDriver->verifyRequest()
#1 /var/www/nams/botman/botman/src/BotMan.php(542): BotMan\BotMan\Drivers\DriverManager::verifyServices()
#2 /var/www/nams/botman/botman/src/BotMan.php(421): BotMan\BotMan\BotMan->verifyServices()
#3 /var/www/nams/app/Http/Controllers/BotManController.php(40): BotMan\BotMan\BotMan->listen()
#4 /var/www/nams/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): App\Http\Controllers\BotManController->handle()...
Steps To Reproduce:
Install botman on laravel 9 from local repository (path)
change in composer/json dependencies to fit laravel 9
Try to connect to facebook like:
$config = [
'user_cache_time' => 720,
'config' => [
'conversation_cache_time' => 720 ,
],
// Your driver-specific configuration
'facebook' => [
'token' => env('FACEBOOK_TOKEN'),
'app_secret' => env('FACEBOOK_APP_SECRET'),
'verification' => env('FACEBOOK_VERIFICATION'),
]
];
$botman = app('botman');
DriverManager::loadDriver(\BotMan\Drivers\Facebook\FacebookDriver::class);
BotManFactory::create($config, new LaravelCache());
$botman->listen();
try to get response for facebook by:
curl -X GET "https://somedomain.org/botman?hub.verify_token=MySecretTokenFromDotENV&hub.challenge=CHALLENGE_ACCEPTED&hub.mode=subscribe"
Function that generates error is below, probably updating it to newest laravel/symfony will work, but I'm not yet so confident to know how to repair this
/**
* #param Request $request
* #return null|Response
*/
public function verifyRequest(Request $request)
{
if ($request->get('hub_mode') === 'subscribe' && $request->get('hub_verify_token') === $this->config->get('verification')) {
return Response::create($request->get('hub_challenge'))->send();
}
}
You can replace
use Symfony\Component\HttpFoundation\Response;
by
use Response; (\Illuminate\Support\Facades\Response)
And in the function do :
/**
* #param Request $request
* #return null|Response
*/
public function verifyRequest(Request $request)
{
if ($request->get('hub_mode') === 'subscribe' && $request->get('hub_verify_token') === $this->config->get('verification')) {
return Response::make($request->get('hub_challenge'))->send();
}
}
At least it worked for me on TwilioDriver

Curl returning null response when run from artisan command for cron job

Trying to run an API which will give me the updated temperature and humidity values but the curl function is not working as it gives a NULL reponse and throws error. running the from the terminal to test it
code:
class updateTempHumHourly extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'update:temphum';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Update temperature and humidity readings hourly';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$options = array(
'cluster' => 'ap2',
'useTLS' => true
);
$pusher = new \Pusher\Pusher(
'osdifnerwion4iownfowinf',
'dofhewofhewofnowenfid',
'7asdkland',
$options
);
$thinkers = t::where('user_id', '!=' , NULL)->where('thinker_status',1)->get();
foreach($thinkers as $t)
{
$temp = [
'action'=>'list_slave',
'mac'=> $t->thinker_MAC,
'type' => 'all',
'appkey' => 'nope'
];
json_encode($temp);
$response = Curl::to('http://103.31.82.46/open/open.php')
->withContentType('application/json')
->withData($temp)
->asJson(true)
->withHeader('Postman-Token: d5988618-676e-430c-808e-7e2f6cec88fc')
->withHeader('cache-control: no-cache')
->post();
foreach($response['slaves'] as $s)
{
if(array_key_exists("temp",$s) && array_key_exists("hum",$s))
{
$slave = sd::where("connected_thinker_MAC",$response['mac'])->where("device_id",$s['slave_id'])->first();
$slave->temperature = $s['temp'];
$slave->humidity = $s['hum'];
$slave->save();
$array = [];
$array['temperature'] = $s['temp'];
$array['humidity'] = $s['hum'];
$array['id'] = $s['slave_id'];
$pusher->trigger($t->user_id."-channel","s-event",$array);
\App\helper\log::instance()->tempHumLog($s);
}
}
}
}
}
the foreach loop throws an error that $response is equal to null. the curl function is not working from here but working fine regularly. help. i need to run this task every hour to get the average temperature and humidity.
Since you said that your code works somewhere that means that there is something wrong with your server and not the code itself probably (since it's a CURL issue).
Inside your php.ini file there is this line : extension=php_curl.dll to enable curl. Uncomment it on your server that you have the crons to make curl work. This should solve your problem.
Testing localy the api you provide us returns a 500 but if you say that it works for you i assume that this is just an example and the problem is in CURL itself.

Not working Custom HTTP Error Pages in laravel 5.2

I use Laravel 5.2
I wanted to change this error :
Whoops, looks like something went wrong.
first please see : Laravel
I created a new file resources/views/errors/404.blade.php but my app error didn't change !
it change just when not found url at route but when insert url injection in to $_GET it show "whoops .." yet
for example work for this link : http://domain.com/dgdgergehrhddg54d6g8
but not working for this injection : http://domain.com/listmanage=8 insert 9 instens of 8
error message when debug is true :
ErrorException: file.php line 215
Trying to get property of non-object
You are viewing that error page because of the environment you are into.
As default, for local environments, the "Whoops" format is shown.
For Production environments, the error/x.blade.php files are used.
To customize this you simply go to: ./app/Exceptions/Handler.php
And modify the render function. You can do something like this:
public function render($request, Exception $e)
{
// If an ErrorException is received and this enviroment is local
if ($e instanceof \ErrorException && app()->environment() == 'local') {
// Show customized page
return response()->view('errors.404', [], $e->getCode());
}
return parent::render($request, $e);
}
Cheers :)
on Larvel 5.2 on your app/exceptions/handler.php just extend this method renderHttpException ie add this method to handler.php
/**
* Render the given HttpException.
*
* #param \Symfony\Component\HttpKernel\Exception\HttpException $e
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function renderHttpException(HttpException $e)
{
// to get status code ie 404, 503, 500
$status = $e->getStatusCode();
if (view()->exists("errors.{$status}")) {
return response()->view("errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
} else {
return $this->convertExceptionToResponse($e);
}
}
Hope that helps.

Prevent Laravel Artisan exceptions from being sent to error reporting

I have a Laravel app that sends its exceptions to an Errbit server.
Here is the code for the exception handler:
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Foundation\Validation\ValidationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Airbrake\Notifier;
class Handler extends ExceptionHandler
{
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
TokenMismatchException::class,
];
public function report(Exception $e)
{
if ($this->shouldReport($e)) {
$options = [
'environment' => app()->environment(),
'host' => config('airbrake.server'),
'projectId' => config('airbrake.api_key'),
'projectKey' => config('airbrake.api_key'),
'rootDirectory' => base_path(),
'secure' => TRUE,
'url' => request()->fullUrl(),
];
$notifier = new Notifier($options);
$notifier->notify($e);
}
return parent::report($e);
}
public function render($request, Exception $e)
{
// Replace `ModelNotFound` with 404.
if ($e instanceof ModelNotFoundException) {
$message = 'Page not found';
if (config('app.debug')) {
$message = $e->getMessage();
}
$e = new NotFoundHttpException($message, $e);
}
$response = parent::render($request, $e);
return $response;
}
}
While this works really well in general, I want to avoid logging errors that happen when I run artisan commands. The whole point of logging errors is to be notified of a problem, but if I'm sitting at the console, I already know about the problem.
I thought of looking in the stack trace to see if artisan is present there, but I see two problems with that:
It doesn't sound like a very efficient thing to be doing.
Queue listeners are also run through artisan, and I do need to get the exceptions from those, because they are not actually being run from the console.
How can I skip exception reporting for all exceptions run from the console, but keep it on for all the others?
The Illuminate\Foundation\Console\Kernel class that actually runs artisan commands has a function reportException which calls your ExceptionHandler's report method.
I added an override of that method to my Kernel class that checks if STDIN is an interactive terminal and disables the error reporting:
protected function reportException(Exception $e)
{
// Disable exception reporting if run from the console.
if (function_exists('posix_isatty') && #posix_isatty(STDIN)) {
echo "Not sending exception report";
return;
}
parent::reportException($e);
}

Resources