Slim redirect works; but also throws an exception - slim

The following code correctly redirects; but also throws an exception:
$app->post("/foo", function () use ($app) {
try {
$app->redirect('/bar');
} catch (Exception $e) {
$app->log->debug("\n" . $e->getFile() . " (Line " . $e->getLine() . ") " . " - " . strftime('%c') . ": Exception (" . $e->getMessage() . ")");
$app->log->debug("\n" . $e->getTraceAsString());
}
});
This is from the Slim log:
/{site root}/Slim/Slim.php (Line 1017) - Wed Sep 17 17:51:33 2014: Exception ()
#0 /{site root}/Slim/Slim.php(1037): Slim\Slim->stop()
#1 /{site root}/Slim/Slim.php(1100): Slim\Slim->halt(302)
#2 /{site root}/index.php(328): Slim\Slim->redirect('/bar')
#3 [internal function]: {closure}()
#4 /{site root}/Slim/Route.php(462): call_user_func_array(Object(Closure), Array)
#5 /{site root}/Slim/Slim.php(1326): Slim\Route->dispatch()
#6 /{site root}/Slim/Middleware/Flash.php(85): Slim\Slim->call()
#7 /{site root}/Slim/Middleware/MethodOverride.php(92): Slim\Middleware\Flash->call()
#8 /{site root}/Slim/Middleware/PrettyExceptions.php(67): Slim\Middleware\MethodOverride->call()
#9 /{site root}/Slim/Slim.php(1271): Slim\Middleware\PrettyExceptions->call()
#10 /{site root}/index.php(689): Slim\Slim->run()
#11 {main}
What am I doing wrong? Or is this a bug in Slim? I can't find any mention of this particular issue.

Slim uses exceptions for route helpers, redirect being one of them. See the "Route Helpers" section in the documentation:
Please be aware that the following application instance method helpers
halt(), pass(), redirect() and stop() are implemented using
Exceptions. Each will throw a \Slim\Exception\Stop or
\Slim\Exception\Pass exception ...
This behavior can be surprising if unexpected.
There are code samples showing the behavior you're experiencing and how to avoid it. The trick is to redirect for error in the catch block and redirect for success after the try/catch block.

Related

How to handle errors thrown within AudioHandler implementations?

For the sake of the argument let's say I have an implementation of BaseAudioHandler in my application:
class AudioPlayerHandler extends BaseAudioHandler {
#override
Future<void> play() async {
throw Error();
}
}
Then when I call this function from an event handler:
void onPlayButtonTap() {
try {
audioPlayerHandler.play();
} catch (error) {
// Error is not caught, but in the console I see unhandled error message.
print(error.toString())
}
}
It doesn't catch the error thrown within the method.
Of course the example this way doesn't make sense, but I've run into this problem when trying to load an invalid url which i could not handle in 'regular' way.
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Instance of 'Error'
#0 AudioPlayerHandler.play (package:audio_service_example/main.dart:197:5)
#1 MainScreen._button.<anonymous closure> (package:audio_service_example/main.dart:145:22)
#2 _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1072:21)
#3 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:253:24)
#4 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:627:11)
#5 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:306:5)
#6 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:239:7)
#7 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:615:9)
#8 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:98:12)
#9 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_ro<…>
I expected to be able to use a try-catch block to handle the error.
I can handle the error inside the audiohandler implementation and let's say I can propagate a custom event that tells the user of the handler that an error occured, but that solution seems to be a bit clumsy.
I'm also not sure if this is a dart programming language quirk unknown to me or an implementation problem? Tried to step through with debugger but did not find anything meaningful.
Could you please help me how this error handling should work?
Thanks you in advance!
This concerns the Dart language.
Because you defined play as an async method, play doesn't actually throw an error. It returns a future which evaluates to an error. If you await that future, you'll be able to catch the error:
try {
await audioPlayerHandler.play();

Netbeans not running PHPUnit tests

I am running PHP7.1 in the latest Netbeans version and am trying to run PHPUnit 6.5 along with it. When I run the tests in Netbeans, they are not executed and the output window gives the following stacktrace:
"C:\bin\phpunit.bat" "--colors" "--log-junit" "C:\Users\rwinkler\AppData\Local\Temp\nb-phpunit-log.xml" "C:\bin\phpunit.phar"
Fatal error: Uncaught PHPUnit\Runner\Exception: Class 'C:\bin\phpunit' could not be found in 'C:\bin\phpunit.phar'. in phar://C:/bin/phpunit.phar/phpunit/Runner/StandardTestSuiteLoader.php:102
Stack trace:
#0 phar://C:/bin/phpunit.phar/phpunit/Runner/BaseTestRunner.php(130): PHPUnit\Runner\StandardTestSuiteLoader->load('C:\\bin\\phpunit', 'C:\\bin\\phpunit....')
#1 phar://C:/bin/phpunit.phar/phpunit/Runner/BaseTestRunner.php(73): PHPUnit\Runner\BaseTestRunner->loadSuiteClass('C:\\bin\\phpunit', 'C:\\bin\\phpunit....')
#2 phar://C:/bin/phpunit.phar/phpunit/TextUI/Command.php(169): PHPUnit\Runner\BaseTestRunner->getTest('C:\\bin\\phpunit', 'C:\\bin\\phpunit....', Array)
#3 phar://C:/bin/phpunit.phar/phpunit/TextUI/Command.php(148): PHPUnit\TextUI\Command->run(Array, true)
#4 C:\bin\phpunit.phar(570): PHPUnit\TextUI\Command::main()
#5 {main}
thrown in phar://C:/bin/phpunit.phar/phpunit/Runner/StandardTestSuiteLoader.php on line 102
PHP Fatal error: Uncaught PHPUnit\Runner\Exception: Class 'C:\bin\phpunit' could not be found in 'C:\bin\phpunit.phar'. in phar://C:/bin/phpunit.phar/phpunit/Runner/StandardTestSuiteLoader.php:102
Stack trace:
#0 phar://C:/bin/phpunit.phar/phpunit/Runner/BaseTestRunner.php(130): PHPUnit\Runner\StandardTestSuiteLoader->load('C:\\bin\\phpunit', 'C:\\bin\\phpunit....')
#1 phar://C:/bin/phpunit.phar/phpunit/Runner/BaseTestRunner.php(73): PHPUnit\Runner\BaseTestRunner->loadSuiteClass('C:\\bin\\phpunit', 'C:\\bin\\phpunit....')
#2 phar://C:/bin/phpunit.phar/phpunit/TextUI/Command.php(169): PHPUnit\Runner\BaseTestRunner->getTest('C:\\bin\\phpunit', 'C:\\bin\\phpunit....', Array)
#3 phar://C:/bin/phpunit.phar/phpunit/TextUI/Command.php(148): PHPUnit\TextUI\Command->run(Array, true)
#4 C:\bin\phpunit.phar(570): PHPUnit\TextUI\Command::main()
#5 {main}
thrown in phar://C:/bin/phpunit.phar/phpunit/Runner/StandardTestSuiteLoader.php on line 102
Done.
My test is a sample test I pulled from a tutorial:
<?php
require_once 'PHPUnit/Autoload.php';
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class EmailTest extends TestCase
{
public function testCanBeCreatedFromValidEmailAddress(): void
{
$this->assertInstanceOf(
Email::class,
Email::fromString('user#example.com')
);
}
public function testCannotBeCreatedFromInvalidEmailAddress(): void
{
$this->expectException(InvalidArgumentException::class);
Email::fromString('invalid');
}
public function testCanBeUsedAsString(): void
{
$this->assertEquals(
'user#example.com',
Email::fromString('user#example.com')
);
}
}
Per xmike in the comments:
"i guess you have misconfigured Project properties -> Testing -> PHPUnit -> Use custom test suite (leave it empty) "

Unique Constraint Violation Magento 2

Very occasionally after a successful checkout the following error shows up on success page / logs:
SagePaySuiteLogger.Exception: Unique constraint violation found
I am using Ebizmarts Sage pay suite 1.2.4 with form integration and Magento 2.2.3 although believe have had the issue for other versions also. I am guessing this is a duplicate entry somehow however hoping for any additional information about what this may be caused by or how to fix.
Trace:
[2018-03-29 08:26:44] SagePaySuiteLogger.Exception: Unique constraint violation found
#0 /home/sites/magento/public_html/vendor/magento/framework/Model/AbstractModel.php(647): Magento\Framework\Model\ResourceModel\Db\AbstractDb->save(Object(Magento\Sales\Model\Order\Payment\Transaction))
#1 /home/sites/magento/public_html/vendor/ebizmarts/sagepaysuite/Model/OrderUpdateOnCallback.php(72): Magento\Framework\Model\AbstractModel->save()
#2 /home/sites/magento/public_html/vendor/ebizmarts/sagepaysuite/Controller/Form/Success.php(172): Ebizmarts\SagePaySuite\Model\OrderUpdateOnCallback->confirmPayment('B1B897CC-D94C-4...')
#3 /home/sites/magento/public_html/vendor/magento/framework/App/Action/Action.php(107): Ebizmarts\SagePaySuite\Controller\Form\Success->execute()
#4 /home/sites/magento/public_html/vendor/magento/framework/Interception/Interceptor.php(58): Magento\Framework\App\Action\Action->dispatch(Object(Magento\Framework\App\Request\Http))
#5 /home/sites/magento/public_html/vendor/magento/framework/Interception/Interceptor.php(138): Ebizmarts\SagePaySuite\Controller\Form\Success\Interceptor->___callParent('dispatch', Array)
#6 /home/sites/magento/public_html/vendor/magento/framework/Interception/Interceptor.php(153): Ebizmarts\SagePaySuite\Controller\Form\Success\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#7 /home/sites/magento/public_html/generated/code/Ebizmarts/SagePaySuite/Controller/Form/Success/Interceptor.php(26): Ebizmarts\SagePaySuite\Controller\Form\Success\Interceptor->___callPlugins('dispatch', Array, Array)
#8 /home/sites/magento/public_html/vendor/magento/framework/App/FrontController.php(55): Ebizmarts\SagePaySuite\Controller\Form\Success\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#9 /home/sites/magento/public_html/vendor/magento/framework/Interception/Interceptor.php(58): Magento\Framework\App\FrontController->dispatch(Object(Magento\Framework\App\Request\Http))
#10 /home/sites/magento/public_html/vendor/magento/framework/Interception/Interceptor.php(138): Magento\Framework\App\FrontController\Interceptor->___callParent('dispatch', Array)
#11 /home/sites/magento/public_html/vendor/magento/module-store/App/FrontController/Plugin/RequestPreprocessor.php(94): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#12 /home/sites/magento/public_html/vendor/magento/framework/Interception/Interceptor.php(135): Magento\Store\App\FrontController\Plugin\RequestPreprocessor->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#13 /home/sites/magento/public_html/vendor/magento/module-page-cache/Model/App/FrontController/BuiltinPlugin.php(73): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#14 /home/sites/magento/public_html/vendor/magento/framework/Interception/Interceptor.php(135): Magento\PageCache\Model\App\FrontController\BuiltinPlugin->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#15 /home/sites/magento/public_html/vendor/magento/framework/Interception/Interceptor.php(153): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#16 /home/sites/magento/public_html/generated/code/Magento/Framework/App/FrontController/Interceptor.php(26): Magento\Framework\App\FrontController\Interceptor->___callPlugins('dispatch', Array, NULL)
#17 /home/sites/magento/public_html/vendor/magento/framework/App/Http.php(135): Magento\Framework\App\FrontController\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#18 /home/sites/magento/public_html/vendor/magento/framework/App/Bootstrap.php(256): Magento\Framework\App\Http->launch()
#19 /home/sites/magento/public_html/pub/index.php(37): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http\Interceptor))
#20 {main}
Code:
This is thrown it seems in the below code:
try {
if (!$this->isModified($object)) {
$this->processNotModifiedSave($object);
$this->commit();
$object->setHasDataChanges(false);
return $this;
}
$object->validateBeforeSave();
$object->beforeSave();
if ($object->isSaveAllowed()) {
$this->_serializeFields($object);
$this->_beforeSave($object);
$this->_checkUnique($object);
$this->objectRelationProcessor->validateDataIntegrity($this->getMainTable(), $object->getData());
if ($this->isObjectNotNew($object)) {
$this->updateObject($object);
} else {
$this->saveNewObject($object);
}
$this->unserializeFields($object);
$this->processAfterSaves($object);
}
$this->addCommitCallback([$object, 'afterCommitCallback'])->commit();
$object->setHasDataChanges(false);
} catch (DuplicateException $e) {
$this->rollBack();
$object->setHasDataChanges(true);
throw new AlreadyExistsException(new Phrase('Unique constraint violation found'), $e);
} catch (\Exception $e) {
$this->rollBack();
$object->setHasDataChanges(true);
throw $e;
}
What does this error mean and how could i fix/debug my magento instance so this no longer occurs?
It may be because of the issue with orders related database entry like for example with the order increment id in main order table. Suppose a case where system tries to enter next order increment id 100000001 and if 100000001 is already available in the order table, then this issue will come.

Struggling in zend acl system

I am new to zend framework and trying to implement zend_acl.I created a custom plugin and placed it in
zend/library/My/Controller/Plugin
zend/library/My/Controller/Helper
where myzend is directory of my project.I am trying to initialize this custom plugin from
bootstrap using
$frontController = Zend_Controller_Front::getInstance();
$frontController->setControllerDirectory('/path/to/controllers')
->setRouter(new Zend_Controller_Router_Rewrite())
->registerPlugin(new My_Controller_Plugin_Acl());
But i am receiving this error message
Fatal error: Uncaught exception 'Zend_Controller_Action_Exception' with message 'Action index" does not exist and was not trapped in __call()' in C:\xampp\htdocs\zend\library\Zend\Controller\Action.php:485
Stack trace:
#0 C:\xampp\htdocs\zend\library\Zend\Controller\Action.php(518): Zend_Controller_Action->__call('indexAction', Array)
#1 C:\xampp\htdocs\zend\library\Zend\Controller\Dispatcher\Standard.php(308): Zend_Controller_Action->dispatch('indexAction')
#2 C:\xampp\htdocs\zend\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#3 C:\xampp\htdocs\zend\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#4 C:\xampp\htdocs\zend\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#5 C:\xampp\htdocs\zend\public\index.php(44): Zend_Application->run()
#6 {main} Next exception 'Zend_Controller_Exception' with message 'Action "index" does not exist and in C:\xampp\htdocs\zend\library\Zend\Controller\Plugin\Broker.php on line 336
Please guide me. Thanks in advance.
In your redirection in your preDispatch() method, try this :
$request->setActionName('error');
Instead of:
$request->setActionName('index');
If you want make an error try this:
throw new Zend_Acl_Exception("Not allowed");
instead of
$request->setControllerName('Error');
$request->setActionName('index');
Put your Plugin in library/Controller/Plugin/Acl.php and then add this in your application (Bootstrap suggested).
//register your folder with aoutloader
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('My_');
//register your plugin
$frontController = Zend_Controller_Front::getInstance();
$frontController->registerPlugin(new My_Controller_Plugin_Acl());
Your code changed default Controller directory so Zend could not find proper Action

How to log SQL query in Zend on Zend_Db_Statement_Exception

When an application error occures on my site and it is connected with malformed SQL query, I'd like to know the query to solve the problem. But it's not easy, when such an error occurs, information is given like this:
An error occurred
Application error
Exception information:
Message: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'p.name' in 'where clause'
Stack trace:
#0 /var/www/ksiegarnia/library/Zend/Db/Statement.php(303): Zend_Db_Statement_Pdo->_execute(Array)
#1 /var/www/ksiegarnia/library/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#2 /var/www/ksiegarnia/library/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query(Object(Zend_Db_Table_Select), Array)
#3 /var/www/ksiegarnia/library/Zend/Db/Select.php(686): Zend_Db_Adapter_Pdo_Abstract->query(Object(Zend_Db_Table_Select))
#4 /var/www/ksiegarnia/library/Zend/Paginator/Adapter/DbSelect.php(142): Zend_Db_Select->query(2)
#5 /var/www/ksiegarnia/library/Zend/Paginator/Adapter/DbSelect.php(183): Zend_Paginator_Adapter_DbSelect->setRowCount(Object(Zend_Db_Table_Select))
#6 [internal function]: Zend_Paginator_Adapter_DbSelect->count()
#7 /var/www/ksiegarnia/library/Zend/Paginator.php(540): count(Object(Zend_Paginator_Adapter_DbTableSelect))
#8 /var/www/ksiegarnia/library/Zend/Paginator.php(1081): Zend_Paginator->getTotalItemCount()
#9 /var/www/ksiegarnia/library/Zend/Paginator.php(753): Zend_Paginator->_calculatePageCount()
#10 /var/www/ksiegarnia/application/modules/default/controllers/IndexController.php(702): Zend_Paginator->setItemCountPerPage(10)
#11 /var/www/ksiegarnia/library/Zend/Controller/Action.php(516): IndexController->searchadvancedAction()
#12 /var/www/ksiegarnia/library/Zend/Controller/Dispatcher/Standard.php(308): Zend_Controller_Action->dispatch('searchadvancedA...')
#13 /var/www/ksiegarnia/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#14 /var/www/ksiegarnia/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()
#15 /var/www/ksiegarnia/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#16 /var/www/ksiegarnia/public_html/index.php(32): Zend_Application->run()
#17 {main}
How to log an SQL query that caused the error?
I've found a quite complicated, but useful solution, which is adding the following code to ErrorController.php:
when the exception is of class Zend_Db_Statement_Exception, go to a specific line of trace, get the Zend_Db_Select argument that was used there and get parts of SQL clause (where, from, order, group etc.) from it and log them into a log file. Nasty, isn't it? ;) But works :)
Here is the code to be inserted into ErrorController.php
$thread_id = exec('echo $$');
if (get_class($errors->exception) == 'Zend_Db_Statement_Exception') {
$trace = $errors->exception->getTrace();
foreach(array('columns', 'from', 'where', 'order', 'group', 'limitcount', 'limitoffset', 'union') as $queryPartName) {
$parts = $trace[2]['args'][0]->getPart($queryPartName);
if ((is_array($parts) && !empty($parts)) ||
(!is_array($parts) && trim($parts) !== '')) {
$log->log($thread_id. "\t".strtoupper($queryPartName) .': ', $priority);
if (is_array($parts)) {
foreach($parts as $part)
$log->log($thread_id. "\t"."\t". (is_array($part) ? 'Array: '. implode(', ', $part) : $part), $priority);
} else
$log->log($thread_id. "\t"."\t". $parts, $priority);
}
}
}