What steps can I take to make a worfklow activity resilient to exceptions - workflow-foundation-4

I am very new to Workflow Foundation development, and am worried that I am opening serious holes in our business process handling by not properly handling application / database exceptions in custom activities.
I would appreciate some steps that I could take to add this resiliency to my custom activities so that I can easily use the designer and other tools to ensure that, as far as I can, I do not create custom activities that are brittle and likely to cause workflow cleanup issues.

Here are some options, at different execution stages, that are available for you to use to handle exceptions.
First option (at activity/workflow execution time):
First of all, on custom activities, you should always try to treat exceptions inside it's execution. Some activities might not work but the overall workflow can continue and, in such cases, log the error to persistence and even show the user that something didn't work as expected but the thing will continue are good options.
That being said there'll always be cases where an activity have to (and even should) thrown exceptions and those should be treated at workflow level. Something like: if this exception occurs on this activity, do this, otherwise, do that.
Lets imagine you've a custom activity which persists something to DB:
public sealed PersistIntegerToDb : CodeActivity
{
public InArgument<int> ValueToPersist { get; set; }
protected override void Execute(CodeActivityMetadata metadata)
{
try
{
// persist
}
catch(SqlException exception)
{
// re throws the SqlException
throw new SqlException("'ValueToPersist' wasn't persisted.", exception);
}
}
}
Then, in your code or through designer you've available TryCatch activity to catch that error and treat it the way you want:
var workflow = new TryCatch
{
Try = new PersistIntegerToDb
{
ValueToPersist = 10
},
Catches =
{
new Catch<SqlException>
{
Action = new ActivityAction<SqlException>
{
Handler = new WriteLine
{
Text = "An error occurred and the value wasn't saved! Anyway workflow will continue..."
}
}
}
}
}
Or you can terminate it using TerminateWorkflow.
Second option (at design time):
Ok, but you can argue that client doesn't know that he have to handle those cases. In that case, and this is an usability option you might consider, instead of making available PersistIntegerToDb on the designer, you can provide an activity already surrounded by exceptions catches to handle, through IActivityTemplateFactory:
public sealed PersistIntegerToDbFactory : IActivityTemplateFactory
{
public Activity Create(DependencyObject target)
{
return new TryCatch
{
Try = new PersistIntegerToDb
{
ValueToPersist = 10
},
Catches =
{
new Catch<SqlException>
{
}
}
};
}
}
Now you just add PersistIntegerToDbFactoryas if it were a regular activity:
new ToolboxItemWrapper(typeof(PersistIntegerToDbFactory), null, "Persist Integer");
Third option (at validation time):
Never forget to validate workflow before execution!
var validationResults =
ActivityValidationServices.Validate(workflow);
foreach(var error in validationResults.Errors)
{
Console.WriteLine(string.Format(
"Validation error '{0}', generated on activity '{1}' in the property named {2}",
error.Message,
error.Source.DisplayName,
error.PropertyName));
}
Fourth option (at application execution time):
You can handle all not treated exception that might happen during execution, using OnUnhandledException event:
var wfApp = new WorkflowApplication(activity);
wfApp.OnUnhandledException +=
delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
{
if (e.UnhandledException is SqlException)
{
Console.WriteLine("Some data wasn't properly persited.");
}
else
{
Console.WriteLine("Unknown error: " + e.UnhandledException.GetType());
Console.WriteLine("With message: " + e.UnhandledException.Message);
}
Console.WriteLine("Ok, workflow will be abort");
return UnhandledExceptionAction.Abort;
};
Note that, at this stage, you can only Abort, Cancel and Terminate the workflow and that's the reason why you should 1) avoid throwing exceptions or 2) treat exceptions inside your workflow. OnUnhandledException is your last chance to end the workflow execution gracefully and should always be treated even if for logging purposes. Something like DivideByZeroExceptions can occur and are almost impossible to predict and catch at validation time, for example.

As far as custom activities goes you should treat them as any other piece of code. Handle the errors you can and let you can't handle the rest bubble up.
At the workflow level you can use the TryCatch activity and workflow persistence to deal with errors. Specially persistence is something people overlook often. Add Persist activities at appropriate steps in your workflow and set the workflow to abort on unhandled errors. Now you can go back in and reload the last good workflow state and retry the actions that cause an unhandled exception. A great way of recovering from failures with resources like databases that might be unavailable for some reason and then come back.

Related

Exception reason/message. Am I reinventing the wheel here?

I want some kind of mechanism to have more information about a caught exception. (Specifically exceptions I throw myself to abort transactions) I've looked around and pretty much the only thing I could find was "Use the info log". This to me does not seem like a good idea. For one it is cumbersome to access and find the last message. And it is limited in size so at some point the new messages won't even show up.
So my idea is the following: Create a class NuException and pass an instance of that through all methods store an instance in the class where the work methods are located. When I need to throw an exception I call a method on it similar to Global::error() but this one takes an identifier and a message.
Once I reach my catch block I can access those from my object the class that contains the work methods similarly to how CLRExceptions work.
class NuException
{
"public" str identifier;
"public" str message;
public Exception error(str _id, str _msg)
{
//set fields
return Exception::Error;
}
}
class Worker
{
"public" NuException exception;
void foo()
{
throw this.exception.error("Foo", "Record Foo already exists");
}
void bar()
{
this.foo();
}
}
void Job()
{
Worker w = new Worker();
try
{
w.bar(ex);
}
catch (Exception::Error)
{
info(w.exception().message());
}
}
It works but isn't there a better way? Surely someone must have come up with a solution to work around this shortcoming in AX?
Short answer: yes.
While your "brilliant" scheme "works", it gets boring pretty fast, as you now must transport your NuException object deep down 20 level from the listener (job) to the thrower (foo). Your bar method and other middle men has no interest or knowledge about your exception scheme but must pass it on anyway.
This is no longer the case after the update.
There are several ways to go.
Use an observer pattern like the Event broker or in AX 2012 and newer use delegates.
Stick to the infolog system and you use an InfoAction class to peggy bag your information to be used later. It can be used to display a stack trace or other interesting information.
Use a dedicated table for logging.
The third way may seem impractical, as any errors will undo the insert in the log. This is the default behavior but can be circumvented.
MyLogTable log;
Connection con = new UserConnection();
con.ttsBegin();
log.setConnection(con);
... // Set your fields
log.insert();
con.ttsCommit();
Your way to go depends on circumstances you do not mention.

JavaFX - Handle Exceptions in one place

I am working on JavaFX application and I want to know if there is a way to handle exceptions in one place.
I am doing inserts into database. And when an insert fails, I get an SQLException.
So, is it possible to handle all SQLExceptions (for all inserts) in one place?
I'm aware of:
Thread.setDefaultUncaughtExceptionHandler(...);
But this is probably not the way to go?
It is bad practice to call any code that executes your SQL query (or any other business logic that may take long to execute) directly in the JavaFX application Thread. (I've observed that under Windows JavaFX applications crash without even printing a stacktrace when an uncaught exeption is thrown in the application thread.)
I would suggest to call your SQL-related code using an javafx.concurrent.Task.
Using the setOnFailed() method you can have code invoked whenever an Execption is thrown. There you can look for the type of exception and call any method that handles your SQLException.
Task<SOME_TYPE> mySqlTask = new Task<>() {
#Override
protected SOME_TYPE call() throws Exception {
... // do sql stuff
return mySqlResult; // or null if not needed
}
};
mySqlTask.setOnFailed(event -> {
Throwable exception = mySqlTask.getException();
if (exception instanceof SQLException) {
// call code that handles the sql exception
}
});
// start the task in a separate thread (or better use an Executor)
new Thread(mySqlTask).start();
By the way, I don't think that using Thread.setDefaultUncaughtExceptionHandler(...); is the way to go neither.

I can't catch an Error

I can't catch the thrown error in my simplified code below. Why is that?
According to requirements of the stackoverflow I must insert some more info but this example is very simple. Can you help me with this example?
package com.myserver {
public class ReturnInfo extends Sprite {
public function ReturnInfo(urlParamsArr:Array) {
try {
var client:HttpClient = new HttpClient();
var uri:URI = new URI("http://valid-url.com/aaa.php");
client.listener.onData = function(event:HttpDataEvent):void {
throw new Error();
};
client.listener.onError = function(event:IOErrorEvent):void {
trace("error");
};
client.postFormData(uri, variables);
}
catch (e:Error){
trace("Error was caught.");
}
}
} //class
} //package
I tried also:
try {
new ReturnInfo(urlParamsArr);
}
catch(e:Error){
trace("caught error");
}
It didn't work either.
The code does not work because the code that throws error is executed later, so you need to use try-catch in the client.listener.onData handler. That handler I assume is called sometimes later so there when you parse or handle the data,make sure to catch/handle the errors
Adding on to what Simion said, the problem is method closure. In order for an exception to be caught somewhere in the "food chain" the catch needs to be in the stack - you will know what is in the current stack by getStackTrace(). In this example, there is no stack pointer that sits at the constructor (or any method) like there is one for client.listener.onData - which is why the postFormData will execute. When the event is triggered it's stack pointer goes back to the origination point of what actually started the event trigger in the first place (not the method that declared it). This is also why the 2nd attempt was unsuccessful.
Add on to the fact that the FP executes discrete chunks in frames (think of this like a heap), anything that executes in the scope of the dispatchEvent will generally have a very small or no stack at all (eg the first stack pointer is usually the dispatcher itself - not a method that actually called it).
try-catch is best attempted within the same scope of a method.
A pseudo example:
function getOrCreateWidget():Widget {
var a:Widget;
try {
a = getWidet();
}
catch(e:TypeError) {
a = createNewWidget();
}
//finally can be debatable - most of us leave it off
//bc it executes anyway just as it would in the function scope.
finally {
a.property = 'foo';
}
return a;
}
If this isn't possible - a last ditch effort is to attach a listener to the loaderInfo.uncaughtErrorEvents. Generally associating this with the systemManager is the best option because the SM knows about every branch of the display tree right down to the root stage. It's neither good practice nor practical to assign all deviations in this method because a lot of context to the programmer is usually lost. It's more an "oh S#!) sorry user, our app just verped."

nhibernate transactions and unit testing

I've got a piece of code that looks like this:
public void Foo(int userId)
{
try {
using (var tran = NHibernateSession.Current.BeginTransaction())
{
var user = _userRepository.Get(userId);
user.Address = "some new fake user address";
_userRepository.Save(user);
Validate();
tran.Commit();
}
}
catch (Exception) {
logger.Error("log error and don't throw")
}
}
private void Validate()
{
throw new Exception();
}
And I'd like to unit test if validations ware made correctly. I use nunit and and SQLLite database for testing. Here is test code:
protected override void When()
{
base.When();
ownerOfFooMethod.Foo(1);
Session.Flush();
Session.Clear();
}
[Test]
public void FooTest()
{
var fakeUser = userRepository.GetUserById(1);
fakeUser.Address.ShouldNotEqual("some new fake user address");
}
My test fails.
While I'm debugging I can see that exception is thrown, Commit has not been called. But my user still has "some new fake user address" in Address property, although I was expecting that it will be rollbacked.
While I'm looking in nhibernate profiler I can see begin transaction statement, but it is not followed neither by commit nor by rollback.
What is more, even if I put there try-catch block and do Rollback explicitly in catch, my test still fails.
I assume, that there is some problem in testing environment, but everything seems fine for me.
Any ideas?
EDIT: I've added important try-catch block (at the beginning I've simplified code too much).
If the exception occurs before NH has flushed the change to the database, and if you then keep using that session without evicting/clearing the object and a flush occurs later for some reason, the change will still be persisted, since the object is still dirty according to NHibernate. When rolling back a transaction you should immediately close the session to avoid this kind of problem.
Another way to put it: A rollback will not rollback in-memory changes you've made to persistent entities.
Also, if the session is a regular session, that call to Save() isn't needed, since the instance is already tracked by NH.

exception (ab)use in web development

I find myself using exception in web development even for conditions that are not really errors, let alone exceptional ones - just logic decisions, validations...
in a web page, I often write code like so:
try
{
int id;
if(!int.TryParse(txtID.Text, out id))
throw new Exception("ID must be an integer");
if(IdAlreadyExists(id))
throw new Exception("ID already exists in database");
//and so on...
}
catch(Exception ex)
{
SetErrorLine(ex.Message);
}
I was wondering if this is really the correct way of using exceptions and enforcing Business Logic in web development.
P.S.: I am using asp.net, and obviously I could use ASP.NET validators for some of these and also seperate UI from logic, but I'm trying to make a point on the general idea.
You've just answered your own question, really.
Exceptions are for exceptional circumstances. Assuming the code you posted is from a page that takes "ID" as input from the user, then it's not exceptional for user input to be bad. Use the validation infrastructure for that, or do it manually, but don't use exceptions for that.
Also, don't get into the habit of displaying Exception.Message to users. It is meant for developers to see to know what went wrong and how to fix it.
I wouldn't consider the first example to be an acceptable use of an Exception. A user could easily screw up entering that information, and user input should be validated anyways.
An exception should be 'exceptional'. Something that you don't expect to happen, shouldn't happen or really don't want to happen. Anything that can be validated or handled before needing to throw an exception should just be treated like an error.
Different communities differ in their acceptable use of exceptions. The Python community is a little bit more liberal with their use of exceptions: http://wiki.sheep.art.pl/Ask%20for%20Forgiveness
I'm a fan of using them as long as it doesn't disrupt the logic of your application.
Just wanted to add that for asp.net adding a global exception handler HttpModule to catch unhandled exceptions is a very clean way to train yourself out of try/catch/finally abuse.
Throw exceptions when the assumptions your methods take on are broken, or if a method simply cannot complete.
In your example, your IdAlreadyExists method might query a database. That method will assume that there is a database to connect to, you have enough memory to do what you need, and so on. If an assumption is broken, throw an exception.
I, for one, like to let lower level code throw exceptions, and higher level code catch exceptions. That's not a hard and fast rule, just a general guideline I like to follow. It's typically not necessary to throw exceptions to the same level, but I could imagine that it would make sense at times.
still missing the way it SHOULD be done
Set an error mesage and return.
Log error and dont display it to user.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
int id = 0;
if(!int.TryParse(txtID.Text, out id))
{
SetErrorLine("Thats not a valid number dude! Need to go to school again");
return;
}
if(IdAlreadyExists(id))
{
SetErrorLine("I already have this entry in store. Sorry. Call again!");
return;
}
...the rest of your code
}
catch(Exception ex)
{
_log.Error(ex);
SetErrorLine("Something unexpected happened dear user ... ");
}
}
Edit: your comment
try {
string error = "";
int id = 10;
if(BO.DoSomething(out error, id, otherParams))
{
SetErrorLine(error);
return;
}
}
catch(Exception ex)
{
//log
}
My guess:
try {
string meaningfullErrorMessage= "";
int id = 10;
if(!BO.DoSomething(out meaningfullErrorMessage, id, otherParams))
{
SetErrorLine(meaningfullErrorMessage);
return;
}
}
catch(Exception ex)
{
//log
}

Resources