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();
Related
This is the code I am using.
I have checked it with different file format but still showing the same error, i have checked the "img.path" its showing the path to the image. I don't understand why I am getting an error.
String targetPath;
var result = await FlutterImageCompress.compressAndGetFile(
img.path,
targetPath,
quality: 88,
format: CompressFormat.webp,
);
Error I am getting:
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: The method 'toLowerCase' was called on null.
Receiver: null
Tried calling: toLowerCase()
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 Validator.checkFileNameAndFormat
package:flutter_image_compress/src/validator.dart:19
#2 FlutterImageCompress.compressAndGetFile
package:flutter_image_compress/flutter_image_compress.dart:150
#3 _AddImageState.uploadFile
package:softclaw/…/addpost/addimage.dart:225
#4 _AddImageState.build.<anonymous closure>
package:softclaw/…/addpost/addimage.dart:97
<asynchronous suspension>
targetPath is the one that goes through the checkFileNameAndFormat > toLowerCase, therefore check to ensure this is not null.
I am trying to use the audio_service package to allow background controls for my podcast playing app. The service does not start. When I call AudioService.start(), nothing is ever returned (I'm awaiting this function and trying to print a statement after this returns, but it never returns. Also, when I first attempt to play an item, it will correctly evaluate AudioService.running to false and then try to start the AudioService (hanging on the start() function). When I hit play a second time, it will evaluate AudioService.running as true (even though the start function never returned) and will then throw this error:
E/flutter ( 8726): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: PlatformException(Attempt to invoke virtual method 'void io.flutter.plugin.common.MethodChannel.invokeMethod(java.lang.String, java.lang.Object, io.flutter.plugin.common.MethodChannel$Result)' on a null object reference, null, null)
E/flutter ( 8726): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:572:7)
E/flutter ( 8726): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:161:18)
E/flutter ( 8726): <asynchronous suspension>
E/flutter ( 8726): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
E/flutter ( 8726): #3 AudioService.play (package:audio_service/audio_service.dart:895:20)
Here is my code which calls the start function:
if(AudioService.running) {
print('playing audio service: ${AudioService.running}');
AudioService.play();
} else {
MediaItem mediaItem = MediaItem(
id: newPostPod.audioUrl,
title: newPostPod.titleTextString(),
artist: newPostPod.subtitleTextString(),
);
print('starting audio service');
bool started = await AudioService.start(
backgroundTaskEntrypoint: _backgroundTaskEntrypoint,
params: {'mediaItem': mediaItem.toJson()},
);
print('audio service started');
if(AudioService.running) {
print('starting to play via media service');
AudioService.playMediaItem(mediaItem);
} else {
print('Audio Service not yet started: $started');
}
}
The code for the background task entrypoint (which is outside of any other class, as it wasn't working inside a class I had read in another issue that it had to be top-level):
_backgroundTaskEntrypoint() {
AudioServiceBackground.run(() => PlayerTask());
}
Lastly, it doesn't appear any of the code within my onStart in my BackgroundAudioTask is running (as print statements at the top of my onStart are not being run). So I'm not sure what's happening here. It isn't give me a clear error or really any hint of where to start debugging audio_service.
Calling AudioService.connect(); before starting the service will solve the error.
For me AudioService.start() would freeze until I added the WAKE_LOCK and FOREGROUND_SERVICE permissions to the AndroidManifest.xml file per the audio_service README file.
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.
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.
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);
}
}
}