I am trying to get all objects from an S3 bucket, but while creating the client by using the factory method, I received an error:
Fatal error: Class 'S3Client' not found in C:\wamp\www\sss.php on line 6
I used the following code:
require 'vendor/autoload.php';
try {
$client = S3Client::factory($credentials);
$arr[] = $client->listObjects(array(
'Bucket'=>'MyglobalBucket1'
));
if ($arr != null) {
var_dump($arr);
}
else {
echo "failed";
}
}
catch(Exception $e) {
echo $e->getMessage();
}
You forgot to use the proper namespace.
use Aws\S3\S3Client;
Related
catch (Exception $e) {
throw new QueryException(
$query, $this->prepareBindings($bindings), $e
);
}
}
1 C:\wamp64\www\laravelProject\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
PDOException::("SQLSTATE[HY000] [2002] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
")
2 C:\wamp64\www\laravelProject\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
PDO::__construct("mysql:host=127.0.0.1;port=3308;dbname=laravelproject", "root", "", [])
use Illuminate\Support\Facades\Schema; <-------------------------ADD THIS
public function boot()
{
Schema::defaultStringLength(191); <-------------------------ADD THIS
}
}
This is the final code.
i have the following code (assume transaction is working properly)
try{
if (!$model->save() {
$return = Yii::t('app/job', 'JOB_NOT_FOUND');
trow new \Exception();
}
} catch(Exception $e) {
$transaction->rollBack();
return (new ApiResponse)->error(null, ApiResponse::EXPECTATION_FAILED, $return);
}
i receiver php error undefined variable return
Any effort is highly appreciated
return is a PHP keyword and could lead to confusion.
Are you using PHP 5.x? PHP keywords are allowed since PHP 7.0.0
Try this:
try{
if (!$model->save() {
throw new \Exception(Yii::t('app/job', 'JOB_NOT_FOUND'));
}
} catch(Exception $e) {
$transaction->rollBack();
return (new ApiResponse)->error(null, ApiResponse::EXPECTATION_FAILED, $e->getMessage());
}
How can i check the availability of Redis connection in Laravel 5.4. I tried below code, but getting an exception with ping line. How can i do, if Redis is not connected than do something else to avoid exception?
No connection could be made because the target machine actively
refused it. [tcp://127.0.0.1:6379]
use Redis;
class SocketController extends Controller
{
public function sendMessage(){
$redis = Redis::connection();
if($redis->ping()){
print_r("expression");
}
else{
print_r("expression2");
}
}
}
Also tried this:
$redis = Redis::connection();
try{
$redis->ping();
} catch (Exception $e){
$e->getMessage();
}
But unable to catch exception
if you are using predis , then it will throw Predis\Connection\ConnectionException
Error while reading line from the server. [tcp://127.0.0.1:6379] <--when redis is not connected
so catch that Exception, you will get your redis is connected or not .
use Illuminate\Support\Facades\Redis;
public function redis_test(Request $request){
try{
$redis=Redis::connect('127.0.0.1',3306);
return response('redis working');
}catch(\Predis\Connection\ConnectionException $e){
return response('error connection redis');
}
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class ConnectionChecker
{
public static function isDatabaseReady($connection = null)
{
$isReady = true;
try {
DB::connection($connection)->getPdo();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
public static function isRedisReady($connection = null)
{
$isReady = true;
try {
$redis = Redis::connection($connection);
$redis->connect();
$redis->disconnect();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
}
I created a helper class to check redis and db connection
Make sure redis is installed
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install redis-server
To test that your service is functioning correctly, connect to the Redis server with the command-line client:
redis-cli
In the prompt that follows, test connectivity by typing:
ping
You should see:
Output
PONG
Install Laravel dependencies
composer require predis/predis
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-redis-on-ubuntu-16-04
https://askubuntu.com/questions/868848/how-to-install-redis-on-ubuntu-16-04
In your constructor you can check redis status connection like this:
/**
* RedisDirectGeoProximity constructor.
* #throws RedisConnectionException
*/
public function __construct()
{
try
{
$this->redisConnection = Redis::connection('default');
}
catch ( Exception $e )
{
throw new RedisConnectionException([
'message' => trans('messages.redis.fail'),
'code' => ApiErrorCodes::REDIS_CONNECTION_FAIL
]);
}
}
and in your exception :
namespace App\Exceptions\Redis;
/**
* Class RedisConnectionException
* #package App\Exceptions\Redis
*/
class RedisConnectionException extends \Exception
{
/**
* RedisConnectionException constructor.
* #param array $options
*/
public function __construct(array $options = [])
{
parent::__construct($options);
}
}
please try with catch (\Exception $e) incl. backslash
Connected to website and keeping idle for 30 mins, then trying to access the entities I am getting the following error.
Entity framework An error occurred while executing the command definition. See the inner exception for details . Inner exception {“Invalid object name 'dbo.TableName'.”}
Sample Code
Static Class Azure
{
public static CrmEntities ConnectCustomerEntity()
{
CrmEntities customerEntity = null;
policy.ExecuteAction(() =>
{
try
{
var shardId = GetShardId();
customerEntity = new CrmEntities(ConnectionStringCustomerDB());
string federationCmdText = #"USE FEDERATION Customer_Federation(ShardId =" + shardId + ") WITH RESET, FILTERING=ON";
customerEntity.Connection.Open();
customerEntity.ExecuteStoreCommand(federationCmdText);
}
catch (Exception e)
{
customerEntity.Connection.Close();
SqlConnection.ClearAllPools();
//throw e;
}
});
return customerEntity;
}
public static CrmEntities DBConnect(CrmEntities _db)
{
try{
if (_db == null)
_db = Azure.ConnectCustomerEntity();
if ((_db.Connection.State == ConnectionState.Broken) || (_db.Connection.State == ConnectionState.Closed))
{
SqlConnection.ClearAllPools();
_db = Azure.ConnectCustomerEntity();
}
else
{ //This code is to find out any issues in connection pool database connection
string sqlCmdText = #"select top 1 Id from Project";
_db.ExecuteStoreCommand(sqlCmdText);
}
}
catch (Exception ex)
{
_db.Connection.Close();
SqlConnection.ClearAllPools();
_db = Azure.ConnectCustomerEntity();
}
return _db;
}
}
Mvc Controller. The following code I am gettting that exception, after 30 mins
public class FilterController : Controller
{
public ActionResult GetFilters(string entityName,string typeFilter)
{
_crmEntities=Azure.DBConnect(_db);
var query = _db.FilterFields.Where(filter => filter.TableId == tableId).ToList(); // Here I am getting that exception
}
}
I dont know, Why i m getting that exception. I tried all possibilities. Nothing helped. I really struck with this. If anybody knows please tell your views to come out from this exception
Thanks in Advance.
I think your session times out.
try to increase session timeout:
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.timeout.aspx
I wanted to write a test for a method in Groovy that throws an IOException. The only way for me to simulate this in the test is to force the method to throw this exception
This is what the original code looks like:
public void cleanUpBermudaFiles(RequestMessage requestMessage)
{
final File sourceDirectory = new File(preferenceService.getPreference("bermuda.landingstrip") + File.separator + requestMessage.getWorkflowId().getValue());
if(sourceDirectory!=null && sourceDirectory.exists())
{
deleteDirectory(sourceDirectory);
}
else
{
LOG.error("Directory must exist in order to delete");
}
}
private void deleteDirectory(File directoryToDelete)
{
try {
FileUtils.deleteDirectory(directoryToDelete);
} catch (Exception e) {
LOG.error("Failed to delete Bermuda files directory located at:" + directoryToDelete.getPath() + "with an exception" + e.getMessage());
}
}
MY TEST: (I'm looking for a way to make deleteDirectory throw IOException)
public void testCleanUpBermudaFailure()
{
workflowId = new WorkflowId("123456")
workflowDirectory = new File(srcDirectory, workflowId.value)
workflowDirectory.mkdir()
File.createTempFile('foo','.lst', workflowDirectory)
def exception = {throw new IOException()}
expect(mockRequestMessage.getWorkflowId()).andReturn(workflowId)
expect(mockPreferenceService.getPreference("bermuda.landingstrip")).andReturn(srcDirectory.path)
replay(mockPreferenceService, mockRequestMessage)
fileCleanUpService.preferenceService = mockPreferenceService
fileCleanUpService.metaClass.deleteDirectory = exception
fileCleanUpService.cleanUpBermudaFiles(mockRequestMessage)
verify(mockPreferenceService, mockRequestMessage)
assert srcDirectory.listFiles().length == 0, 'CleanUp failed'
}
If the service class is a Groovy class, you would want to mock FileUtils like:
FileUtils.metaClass.static.deleteDirectory = { File f -> throw new IOException() }
However, as ataylor pointed out, you cannot intercept calls if it's a Java class. You can find a nice blog post about it here.
You are mocking a no-arg call to deleteDirectory, but the real deleteDirectory takes one argument of type File. Try this:
def exception = { File directoryToDelete -> throw new IOException() }
...
fileCleanUpService.metaClass.deleteDirectory = exception