typo3 flow: catch exception and forward back to originating action - flow-framework

In my typo3 flow app I want to stop execution after throwing an exception as flash-message. Therefore I wrote this:
public function updateAction(Mitglied $mitglied) {
if ($xy == 'z') {
try {
throw new \TYPO3\Flow\Validation\Exception\InvalidValidationOptionsException('Fehler: In dieser Kombination nicht zulässig', 1);
} catch (\TYPO3\Flow\Validation\Exception\InvalidValidationOptionsException $e) {
$this->flashMessageContainer->addMessage(new \TYPO3\Flow\Error\Error($e->getMessage()));
}
}
$this->mitgliedRepository->update($mitglied);
$this->addFlashMessage('Mitglied erfolgreich geändert.');
$this->redirect('index');
}
The message ist shown, as I wanted, as flash-message. But the execution of the function doesn't stop. Does anybody know, why and how to prevent? A redirect to the originating action would be desired for the case, that the if-condition is true.

I got it now with the following code:
// get back to originating request - see https://git.typo3.org/Packages/TYPO3.Flow.git/blob/master:/Classes/TYPO3/Flow/Mvc/Controller/ActionController.php
$referringRequest = $this->request->getReferringRequest();
if ($referringRequest === NULL) {
return;
}
$packageKey = $referringRequest->getControllerPackageKey();
$subpackageKey = $referringRequest->getControllerSubpackageKey();
if ($subpackageKey !== NULL) {
$packageKey .= '\\' . $subpackageKey;
}
$argumentsForNextController = $referringRequest->getArguments();
$argumentsForNextController['__submittedArguments'] = $this->request->getArguments();
$argumentsForNextController['__submittedArgumentValidationResults'] = $this->arguments->getValidationResults();
$this->forward($referringRequest->getControllerActionName(), $referringRequest->getControllerName(), $packageKey, $argumentsForNextController);
In the end this is much easier:
$this->errorAction()->forwardToReferringRequest();

Related

Why does the error method return an error?

I want to validate input corresponding to the following grammar snippet:
Declaration:
name = ID "=" brCon=BracketContent
;
BracketContent:
decCon=DecContent (comp+=COMPARATOR content+=DecContent)*
;
DecContent:
(neg=("!"|"not"))? singleContent=VarContent (op+=OPERATOR nextCon+=VarContent)*
;
My validation looks like that:
#Check
def checkNoCycleInHierarchy(Declaration dec) {
if(dec.decCon.singleContent.reference == null) {
return
}
var names = newArrayList
var con = dec.decCon.singleContent
while(con.reference != null) {
con = getThatReference(con).singleContent
if(names.contains(getParentName(con))) {
val errorMsg = "Cycle in hierarchy!"
error(errorMsg,
SQFPackage.eINSTANCE.bracketContent_DecCon,
CYCLE_IN_HIERARCHY)
return
}
names.add(getParentName(con))
}
}
But when I test this validation with a testCaseit returns me an error message:
Expected ERROR 'raven.sqf.CycleInHierarchy' on Declaration at [-1:-1] but got
ERROR (org.eclipse.emf.ecore.impl.EClassImpl#5a7fe64f (name: Declaration) (instanceClassName: null) (abstract: false, interface: false).0) 'Error executing EValidator', offset null, length null
ERROR (org.eclipse.emf.ecore.impl.EClassImpl#5a7fe64f (name: Declaration) (instanceClassName: null) (abstract: false, interface: false).0) 'Error executing EValidator', offset null, length null
I just can't figure out what's wrong with it so I hope that someone of you might have an idea.
Greetings Krzmbrzl
You test utility tells you that the validator did not produce the expected validation error ("CycleInHierarchy").
Instead, the validator produced the error "Error executing EValidator".
Which means an exception has been thrown when your validator was executed.
It turned out it was an internal error...I'm still not exactly sure what went wrong but I have rewritten my validation method and now it works as expected.
Now the method looks like this:
enter code here#Check
def checkNoCycleInHierarchy(Declaration dec) {
if(dec.varContent.reference == null) {
//proceed only if there is a reference
return
}
var content = dec.varContent
var names = newArrayList
while(content.reference != null && !names.contains(getParentName(content))) {
names.add(getParentName(content))
content = content.reference.varContent
if(names.contains(getParentName(content))) {
val errorMsg = "Cycle in hierarchy!"
error(errorMsg,
SQFPackage.eINSTANCE.declaration_BrCon,
CYCLE_IN_HIERARCHY)
return
}
}
}
I have the suspicion that there was a problem with the usage of my "getThatReference" in this case.
Greeting Krzmbrzl

FromOutcome for `Switch Node` directing flow to `Method Call Node` don't wont to work

I have difined my flow as:
builder.id("", PublisherBean.PUBLISHER_FLOW_NAME);
builder.viewNode("list", "/pages/publishers.xhtml");
builder.viewNode("details", "/pages/publishers-details.xhtml");
builder.viewNode("deleted", "/pages/publishers-deleted.xhtml");
builder.viewNode("form", "/pages/publishers-form.xhtml");
builder.viewNode("exit", "/index.xhtml");
builder.methodCallNode("invoke-update")
.expression("#{publisherBean.update()}")
.defaultOutcome("details");
builder.methodCallNode("switch-fail")
.defaultOutcome("invoke-publishers")
.expression("#{publisherBean.switchFail()}");
builder.switchNode("proceed-action-request")
.defaultOutcome("switch-fail")
.switchCase()
.condition("#{publisherBean.actionType.ifEdit()}").fromOutcome("form");
builder.switchNode("go-for-it")
.defaultOutcome("switch-fail")
.switchCase()
.switchCase()
.condition("#{publisherBean.actionType.ifEdit()}").fromOutcome("invoke-update");
as you can see, there is two switch nodes. First directs to a View Node, second one is trying to direct to a Method Call Node.
First one works fine, however second is giving me a headache. Second one is giving me an error
Unable to find matching navigation case with from-view-id '/pages/publishers-form.xhtml' for action '#{publisherBean.proceed()}' with outcome 'proceed-form'.
proceed function is just
public String proceed() {
LOG.log(Level.OFF, "Form proceed in action type {0}", actionType);
return "go-for-it";
}
Logged info confirms, that publisherBean.actionType.ifEdit() returns true, however that fact is ignored. If i change outcome from invoke-update to form or any other View Node id, then it "works fine".
Is it i'm doing something wrong, or Method Call Node cant be used as an outcome to a Switch Node?
I run into this issue too. In my case the problem is in calling Method Call Node after another Method Call Node.
I invesigated it a bit and found a problem in: com.sun.faces.application.NavigationHandlerImpl.synthesizeCaseStruct method. This method is used to determine where to go from methodCallNode or switchCallNode and it only looks at viewNodes and returnNodes.
private CaseStruct synthesizeCaseStruct(FacesContext context, Flow flow, String fromAction, String outcome) {
CaseStruct result = null;
FlowNode node = flow.getNode(outcome);
if (null != node) {
if (node instanceof ViewNode) {
result = new CaseStruct();
result.viewId = ((ViewNode)node).getVdlDocumentId();
result.navCase = new MutableNavigationCase(fromAction,
fromAction, outcome, null, result.viewId,
flow.getDefiningDocumentId(), null, false, false);
} else if (node instanceof ReturnNode) {
String fromOutcome = ((ReturnNode)node).getFromOutcome(context);
FlowHandler flowHandler = context.getApplication().getFlowHandler();
try {
flowHandler.pushReturnMode(context);
result = getViewId(context, fromAction, fromOutcome, FlowHandler.NULL_FLOW);
// We are in a return node, but no result can be found from that
// node. Show the last displayed viewId from the preceding flow.
if (null == result) {
Flow precedingFlow = flowHandler.getCurrentFlow(context);
if (null != precedingFlow) {
String toViewId = flowHandler.getLastDisplayedViewId(context);
if (null != toViewId) {
result = new CaseStruct();
result.viewId = toViewId;
result.navCase = new MutableNavigationCase(context.getViewRoot().getViewId(),
fromAction,
outcome,
null,
toViewId,
FlowHandler.NULL_FLOW,
null,
false,
false);
}
}
} else {
result.newFlow = FlowImpl.SYNTHESIZED_RETURN_CASE_FLOW;
}
}
finally {
flowHandler.popReturnMode(context);
}
}
} else {
// See if there is an implicit match within this flow, using outcome
// to derive a view id within this flow.
String currentViewId = outcome;
// If the viewIdToTest needs an extension, take one from the currentViewId.
String currentExtension;
int idx = currentViewId.lastIndexOf('.');
if (idx != -1) {
currentExtension = currentViewId.substring(idx);
} else {
// PENDING, don't hard code XHTML here, look it up from configuration
currentExtension = ".xhtml";
}
String viewIdToTest = "/" + flow.getId() + "/" + outcome + currentExtension;
ViewHandler viewHandler = Util.getViewHandler(context);
viewIdToTest = viewHandler.deriveViewId(context, viewIdToTest);
if (null != viewIdToTest) {
result = new CaseStruct();
result.viewId = viewIdToTest;
result.navCase = new MutableNavigationCase(fromAction,
fromAction, outcome, null, result.viewId,
null, false, false);
}
}
return result;
}

Error handling in Dart with throw catch. (Catch doesn't seem to execute)

I'm trying out Dart for the first time and I can't get the error handling to work for me. Here's some information about it.
Resources:
Gist with HTML, CSS and Dart: gist.github.com/enjikaka/8164610
ZIP with the project: ge.tt/6StW4cB1/v/0?c
JavaScript version on CodePen: codepen.io/enjikaka/pen/giurk
How I want it:
Making an instance of MinecraftSkin should throw an StateError if the image source returns a 403 error code. The exception should be handled in the generateHead() function where the instance of MineCraft skin is attempted to be made.
How it is:
If an image representing the skin of a MineCraft player does not exist (when the image source does not exist and returns 403) the code stops on line 22 (onError; where I throw the StateError) and prints to console "Breaking on exception: Bad state: User has no skin".
However, in the catch on generateHead, nothing gets executed. It doesn't print the StateError message when I prompt it to, neither does it insert the StateError message to the selected element in the DOM.
Code
import 'dart:html';
class MinecraftSkin {
String user;
CanvasElement ce = new CanvasElement();
void _generateCanvas(Event e) {
CanvasRenderingContext2D ctx = ce.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.drawImageScaledFromSource((e.target as ImageElement),8,8,8,8,0,0,ce.width,ce.height);
}
CanvasImageSource getHead() => ce;
String name() => user;
MinecraftSkin(String minecraftUser, num size) {
user = (minecraftUser == null) ? 'Notch' : minecraftUser;
ce.width = size;
ce.height = size;
ImageElement img = new ImageElement()
..onLoad.listen(_generateCanvas)
..onError.listen((_) => throw new StateError('User has no skin'));
img.src = "http://s3.amazonaws.com/MinecraftSkins/"+user+".png";
}
}
void generateHead(Event e) {
MinecraftSkin ms;
try {
ms = new MinecraftSkin((querySelector('#userName') as InputElement).value, 128);
} on StateError catch(se) {
print(se.message);
querySelector('#status').text = se.message;
}
CanvasElement cems = ms.getHead();
cems.id = "mc" + ms.name();
cems.title = "mc" + ms.name();
document.body.append(cems);
querySelector('#status').text = "Got head!";
}
void main() {
querySelector('#generateHead').onClick.listen(generateHead);
}
Thanks in advance!
Sincerely, Jeremy
The image listeners (onLoad, onError) are asynchronous. The MincraftSkin instantiation is completed without any errors, and only after the image resource is loaded or an error is received, is the StateError thrown, probably several hundred milliseconds later. The constructor does not wait around to see if the image will properly load or not.

How can I access the result of the response of HttpRequest in Dart?

After many attempts to get the content of the response in HttpRequest, I failed completely to know or understand why I can't have what I want, and I must mention that I can log and manipulate the response only inside an onReadyStateChange (onLoad and onLoadEnd are giving me the same results!), but I really want that value outside the callback.
Here is the part of code that I'm stuck with
Map responsData;
req=new HttpRequest()
..open(method,url)
..send(infojson);
req.onReadyStateChange.listen((ProgressEvent e){
if (req.readyState == HttpRequest.DONE ){
if(req.status == 200){
responsData = {'data': req.responseText};
print("data receaved: ${ req.responseText}");
//will log {"data":mydata}
}
if(req.status == 0){
responsData = {'data':'No server'};
print(responsData );
//will log {"data":No server}
}
}
});
//anything here to get responsData won't work
You have to assign an onLoad callback before you call send.
I'm not sure what you mean with only inside an onReadyStateChange.
Maybe you want to assign the responseText to a variable outside the the callback.
Create a method:
Future<String> send(String method, String url, String infojson) {
var completer = new Completer<String>();
// var result;
req=new HttpRequest()
..open(method,url)
..onLoad.listen((event) {
//print('Request complete ${event.target.reponseText}'))
// result = event.target.responseText;
completer.complete(event.target.responseText);
})
..send(infojson);
return completer.future;
}
and call this method like
var result;
send(method, url).then(
(e) {
// result = e;
print('Request complete ${e}'));
});

calling a webservice from scheduled task agent class in windows phone 7.1

Can we call a webservice from the scheduled periodic task class firstly, if yes,
Am trying to call a webservice method with parameters in scheduled periodic task agent class in windows phone 7.1. am getting a null reference exception while calling the method though am passing the expected values to the parameters for the webmethod.
am retrieving the id from the isolated storage.
the following is my code.
protected override void OnInvoke(ScheduledTask task)
{
if (task is PeriodicTask)
{
string Name = IName;
string Desc = IDesc;
updateinfo(Name, Desc);
}
}
public void updateinfo(string name, string desc)
{
AppSettings tmpSettings = Tr.AppSettings.Load();
id = tmpSettings.myString;
if (name == "" && desc == "")
{
name = "No Data";
desc = "No Data";
}
tservice.UpdateLogAsync(id, name,desc);
tservice.UpdateLogCompleted += new EventHandler<STservice.UpdateLogCompletedEventArgs>(t_UpdateLogCompleted);
}
Someone please help me resolve the above issue.
I've done this before without a problem. The one thing you need to make sure of is that you wait until your async read processes have completed before you call NotifyComplete();.
Here's an example from one of my apps. I had to remove much of the logic, but it should show you how the flow goes. This uses a slightly modified version of WebClient where I added a Timeout, but the principles are the same with the service that you're calling... Don't call NotifyComplete() until the end of t_UpdateLogCompleted
Here's the example code:
private void UpdateTiles(ShellTile appTile)
{
try
{
var wc = new WebClientWithTimeout(new Uri("URI Removed")) { Timeout = TimeSpan.FromSeconds(30) };
wc.DownloadAsyncCompleted += (src, e) =>
{
try
{
//process response
}
catch (Exception ex)
{
// Handle exception
}
finally
{
FinishUp();
}
};
wc.StartReadRequestAsync();
}
private void FinishUp()
{
#if DEBUG
try
{
ScheduledActionService.LaunchForTest(_taskName, TimeSpan.FromSeconds(30));
System.Diagnostics.Debug.WriteLine("relaunching in 30 seconds");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
#endif
NotifyComplete();
}

Resources