Thanks for reading my problem,
I am trying to add middleware to slim framework but it encounter with an error
Uncaught InvalidArgumentException: All Route middleware must be callable
$authenticateForRole = function ( $user_Id, $tokenKey ) {
try {
// my stuffs
}
} catch (\Throwable $th) {
echo $th->getMessage();
return false;
}
};
$app->map('/averageresponsetime/',$authenticateForRole($UserId, $token), function () use ($app) {
echo json_encode($post1);
})->via('POST');
$app->run();
i think you should use a clousure as the documentation states;
$authenticateForRole = function ( $user_Id, $tokenKey ) {
return function () use ( $user_Id, $tokenKey ) {
try {
// my stuffs
}
} catch (\Throwable $th) {
echo $th->getMessage();
return false;
}
}
};
Related
So I need some help on building out one of my methods for retrieving twitter lists using IDs. Below, I will describe and go into detail on what it's returning.
Code:
public static function get_list($list_id)
{
$lists = self::get_lists();
$params = [
'list.fields' => 'created_at,follower_count,member_count,private,description,owner_id',
'user.fields' => 'created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld'
];
try {
$list = $lists->get($list_id, $params);
} catch (\GuzzleHttp\Exception\ClientException $e) {
return $e;
}
return $list;
}
When $lists->get() has an issue, it throws the following items object(GuzzleHttp\Exception\ClientException)#1640 (10) { ["request":"GuzzleHttp\Exception\RequestException":private]=> error.
What I'd like to achieve:
Return $e so that I can read the error (Unable to get this to work).
If I switch out return $e for return 'Hello', I still see the object and not the string.
The IDE suggests that it #throws GuzzleException.
Does anyone see anything wrong in how I'm handling my exception and why I'm unable to properly return the exception error?
Try to use exception hierarchy to catch any exception. ClientException only catches status code between 400x-499. To catch other exception or catch within the same Exception you can use RequestException.
public static function get_list($list_id)
{
$lists = self::get_lists();
$params = [
'list.fields' => 'created_at,follower_count,member_count,private,description,owner_id',
'user.fields' => 'created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld'
];
try {
$list = $lists->get($list_id, $params);
if($list->getStatusCode() == 200)){
$return_list = json_decode($list->getBody(),true);
}
} catch (\GuzzleHttp\Exception\ClientException $e) {
$error['error'] = $e->getMessage();
$error['request'] = $e->getRequest();
if($e->hasResponse()){
// you can pass a specific status code to catch a particular error here I have catched 400 Bad Request.
if ($e->getResponse()->getStatusCode() == '400'){
$error['response'] = $e->getResponse();
}
}
return $error;
} catch(\GuzzleHttp\Exception\RequestException $se){
$error['error'] = $e->getMessage();
$error['request'] = $e->getRequest();
return $error;
} catch(Exception $e){
//other errors
}
return $list;
}
I have this code:
try{
firstMethod()
secondMethod()
}
catch(Exception $e){
....
}
What I want is execute all try/catch block functions but capturing if one throws exception, without skipping the following methods
a possible but not pretty code would be:
try{
firstMethod();
}
catch(Exception $e){
....
}
try{
secondMethod();
}
catch(Exception $e){
....
}
I am assuming you might have a lot of those if you are looking for more convenient way than "not pretty" take?
I would say just loop through them:
foreach ( [ 'firstMethod', 'secondMethod' ] as $callable ) {
try {
$callable();
}
catch ( Exception $e ) {
}
}
Why not write try catch in each function and log the exceptions somewhere.
function firstMethod() {
try {
//code
}
catch (Exception $e) {
logException($e);
}
}
function secondMethod() {
try {
//code
}
catch (Exception $e) {
logException($e);
}
}
function mainMethod() {
firstMethod();
secondMethod();
}
This will help in doing something like this:
function someOtherMethod() {
secondMethod();
}
I had 2 tables . driver and part_time_available, when I select driver type parttime it'll show part_time_available field. the problem is I can't save.
it throws this error : Integrity constraint violation: 1048 Column 'driver_id' cannot be null
here's my save controller code so far :
public function save(Request $request, $obj = null) {
if (!$obj) {
$obj = new Driver;
}
$obj->active = TRUE;
$obj->counter = 0;
return $this->saveHandler($request, $obj);
}
public function saveHandler(Request $request, $obj)
{
try {
DB::beginTransaction();
$obj->fill($request->all());
if (!$obj->save()) {
throw new ValidationException($obj->errors());
}
foreach($request->parttimeAvailabilities as $pta) {
if (empty($pta['id'])) {
$parttimeAvailability = new ParttimeAvailability();
}
else {
$parttimeAvailability = ParttimeAvailability::find($pta['id']);
}
$parttimeAvailability->Driver()->associate($obj);
$pta['driver_id'] = isset($pta['driver_id']) ? $pta['driver_id'] : null;
$driver = Driver::find($pta['driver_id']);
$parttimeAvailability->driver()->associate($driver);
$parttimeAvailability->day = $pta['day'];
$parttimeAvailability->start_time = $pta['start_time'];
$parttimeAvailability->end_time = $pta['end_time'];
$parttimeAvailability->available = isset($pta['available']);
$parttimeAvailability->save();
};
$obj->save();
if (!$parttimeAvailability->save()) {
throw new ValidationException($parttimeAvailability->errors());
}
DB::commit();
return $this->sendSuccessResponse($request);
} catch (ValidationException $e) {
DB::rollback();
\Log::error($e->errors);
return $this->sendErrorResponse($request, $e->errors);
} catch (Exception $e) {
DB::rollback();
\Log::error($e->getMessage());
return $this->sendErrorResponse($request,'Unable to process. Please contact system Administrator');
}
}
any idea ??
Take a look here:
$pta['driver_id'] = isset($pta['driver_id']) ? $pta['driver_id'] : null;
$driver = Driver::find($pta['driver_id']);
From this code chunk we can see that driver_id can be null. In that case there is no driver to find. You should only search for a driver if you have an id.
I have a form which represnts single answer object (this is standard propel generated form I have not changed much there only some validation rules) and another form that represents a collection of answers code as below:
class BbQuestionAnswersForm extends sfForm {
public function __construct($defaults = array(), $options = array(), $CSRFSecret = null) {
parent::__construct($defaults, $options, $CSRFSecret);
}
public function configure() {
if (!$questions = $this->getOption('questions')) {
throw new InvalidArgumentException('The form need array of BbExamQuestion objects.');
}
if (!$taker = $this->getOption('taker')) {
throw new InvalidArgumentException('The form need BbExamtaker object.');
}
if (!$user = $this->getOption('questions')) {
throw new InvalidArgumentException('The form need sfGuardUser object.');
}
foreach($questions as $question) {
$answer = new BbExamAnswer();
$answer->setBbExamQuestion($question);
$answer->setBbExamTaker($taker);
$answer->setCreatedBy($user);
$answer->setUpdatedBy($user);
$form = new BbExamAnswerForm($answer, array('question' => $question));
$this->embedForm($question->getId(), $form);
}
$this->widgetSchema->setNameFormat('solve[%s]');
}
}
Everything(validation, display) goes fine with this form until I try to save it. Part of action which trying to save the form:
...
$this->form = new BbQuestionAnswersForm(null, array('questions' => $this->questions, 'taker' => $this->taker, 'user' => $this->getUser()->getGuardUser()));
if($request->isMethod('post')) {
$this->form->bind($request->getParameter($this->form->getName()));
if($this->form->isValid()) {
if($this->form->save()) {
$this->getUser()->setFlash('success', 'Save goes fine.');
$this->redirect($this->generateUrl('#bb'));
} else {
$this->getUser()->setFlash('error', 'Upps an error occurred.');
}
}
}
When I send valid form I receive "Call to undefined method BbQuestionAnswersForm::save()" error.
I tried to write this method like this:
public function save() {
$conn = Propel::getConnection(ZlecPeer::DATABASE_NAME);
$conn->beginTransaction();
try{
foreach($this->getEmbeddedForms() as $form) {
$form->save();
}
$conn->commit();
} catch(Exception $e) {
$conn->rollback();
echo 'upps something goes wrong';
die($e->getMessage());
return false;
}
return true;
}
but it doesnt work, I receive exception without any message.
What am I doing wrong, how to make save method work?
I believe your BbQuestionAnswersForm is extending the wrong object. It should extend BaseFormDoctrine or possibly BaseBbQuestionAnswersForm if you are using the framework correctly.
Edit: Just noticed you are using propel but it should be the same thing. Try:
class BbQuestionAnswersForm extends BaseBbQuestionAnswersForm
and less likely:
class BbQuestionAnswersForm extends BaseFormPropel
Save method should looks like this:
public function save($con = null) {
if (null === $con) {
$con = Propel::getConnection(BbExamAnswerPeer::DATABASE_NAME);
}
$con->beginTransaction();
try{
foreach($this->embeddedForms as $name => $form) {
if(!isset($this->values[$name]) || !is_array($this->values[$name])) {
continue;
}
if($form instanceof sfFormObject) {
$form->updateObject($this->values[$name]);
$form->getObject()->save($con);
$form->saveEmbeddedForms($con);
} else {
throw new Exception('Embedded form should be an instance of sfFormObject');
}
}
$con->commit();
} catch(Exception $e) {
$con->rollBack();
throw $e;
return false;
}
return true;
}
I wanted to add an action on Sales>Order in Magento admin.
Screenshot-
I followed the second method from this blog- www.blog.magepsycho.com/adding-new-mass-action-to-admin-grid-in-magento/
My problem-
I am not able to get the order id (for performing the action on it) in the action controller.
My code in class MyPackage_MyModule_IndexController extends Mage_Adminhtml_Controller_Action
protected function _initOrder()
{
$id = $this->getRequest()->getParam('order_id'); ///TROUBLE HERE
$order = Mage::getModel('sales/order')->load($id);
if (!$order->getId()) {
$this->_getSession()->addError($this->__('This order no longer exists.'));
$this->_redirect('dash/sales_order');
$this->setFlag('', self::FLAG_NO_DISPATCH, true);
return false;
}
Mage::register('sales_order', $order);
Mage::register('current_order', $order);
return $order;
}
public function approvecodAction() {
if ($order = $this->_initOrder()) {
try {
$order->setStatus('codapproved')
->save();
$this->_getSession()->addSuccess(
$this->__('The order has been approved for COD.')
);
}catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
}catch (Exception $e) {
$this->_getSession()->addError($this->__('The order has not been approved for COD.'));
Mage::logException($e);
}
$this->_redirect('*/sales_order/view', array('order_id' => $order->getId()));
}
}
Note I copied the above two functions from app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php and modified for my purpose.
Please tell me how and where to set the parameter order id? Or if they are getting set, then how to get them?
Thanks!
You're dealing with a mass action callback on the controller, so you will be getting an array of values in the parameter instead of a single value. You're going to need to do something more like this in your action method:
public function approvecodAction() {
$orderIds = $this->getRequest()->getPost('order_ids', array());
foreach ($orderIds as $orderId) {
$order = Mage::getModel('sales/order')->load($orderId);
try {
$order->setStatus('codapproved')
->save();
$this->_getSession()->addSuccess(
$this->__('The order has been approved for COD.')
);
}catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
}catch (Exception $e) {
$this->_getSession()->addError($this->__('The order has not been approved for COD.'));
Mage::logException($e);
}
}
$this->_redirect('*/sales_order/view', array('order_id' => $order->getId()));
}
Hope that helps!