Best practise to handle exceptions between actor and client in service fabric - exception

I am wondering what the best practise approach is to throwing/handling exceptions between Actors and clients within the service fabric.
I noticed for example that when an exception was thrown from an Actor the client received a nested set of exceptions. The outer exception is of type System.AggregateException and merely indicates that "One or more errors occurred". But if you drill down to the actual inner exceptions, you see that the exception that was thrown from the Actor cannot be serialized.
Test method PoCSystem.Test.CommandHandlerTest.CommandHandler_When_ExpectExceptionThrown threw exception:
System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. --->
System.AggregateException: One or more errors occurred. ---> System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]:
Type 'PoCActor.Interfaces.ConcurrencyException' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.
If you then mark the Exception with DataContract and DataMember attributes the Exception then complains that it is not compatible with serialization.
What is the best approach for error handling in the service fabric?

Consider using old-school .net serializability. From the "Exception" code snippet built in to visual studio:
[Serializable]
public class MyException : Exception
{
public MyException() { }
public MyException(string message) : base(message) { }
public MyException(string message, Exception inner) : base(message, inner) { }
protected MyException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}

Related

Difference between throwing Exception and throwing a specific Exception such as NullPointerException

I am wondering what is the difference between throwing just Exception and throwing a specific Exception such as NullPointer Exception.
To my current knowledge an Exception should be able to catch any type of exception where as using a specific Exception expects that only that exception type can be thrown.
Example:
void test(String testString) throws Exception;
vs
void test(String testString) throws NullPointerException;
If this is correct than to me it makes sense to just always throw Exception and to never name a specific exception. Am I missing something important here? Does it at the very least effect performance at all? A lot of people are looking between throwing and catching exceptions but nobody asks this very basic question.
I do not see a benefit of throwing any exception except Exception.
To start off, Exception is a base type of every Exception. Just like object is for everything.
By throwing a specific Exception you provide more information to the consumer of what has happened.
Imagine scenario where you get a plain Exception without a message, consumer is lost. When for example framework throws a NullReferenceException, then you are aware of a fact that one of your objects does not have a reference which it was trying to access.
This is how you can chain exceptions and make use of their types:
try
{
throw new NotImplementedException();
}
catch(NullReferenceException ex)
{
// Logic for NullReference exception if needed.
}
catch(NotImplementedException ex)
{
// This will be executed.
}
catch(Exception ex)
{
// Will catch every exception.
}
There are at least two reasons why you would want to throw a specific kind of exception:
If a program fails with an exception, you will have more information with which to determine what went wrong. Compare seeing Exception with FileNotFoundException. The latter clearly gives you more information.
In some cases, the code will want to catch certain kinds of exceptions. For example, when working with serial ports, you might want to catch and handle a TimeoutException differently from a NullReferenceException.
The NullPointerException you mentioned is a very good example from the regular Exception because it is a subclass of RuntimeException. Any throwing of (a subclass of) RuntimeException does not have to be caught or declared.
Any other (=not a subclass of RuntimeException) Exception has to be handled in your code by either a try/catch block or a throws declaration. Otherwise, your code will not even compile! That forces you as a developer to handle errors that might pop up.
As for why using different Exception types is useful, consider the following simple example that uses multiple catch statements:
void doDBStuff(){
try {
performStatement(someStatement);
} catch(SQLException e){
//invalid SQL syntax, something is broken
} catch(AuthenticationException e){
//invalid user credentials for the db, inform the user to change these values
}
In this example, two different exceptions end up in two different catch blocks which lets you handle these errors differently.
It's a best practice to throw specific exceptions, instead of a generic one. This is because the caller might want to treat the exceptions differently, for example in a WebApi you might want to return a Bad Request response (400) for a ArgumentNullException, but you might want to return a different result for other types of exceptions. For example you might actually throw a custom NotFoundException and then the controller would catch it and return a Not Found response (404) instead.
Basically if you throw specific exceptions you are allowing the consumer code to handle the different exception scenarios the way they want.

Mule private flows and separation of concerns

I have a requirement which I want to solve using Mule. My flow design follows like:
A main-flow with request-response HTTP inbound endpoint. After applying couple of transformations on the current payload this main flow invokes two private flows namely private-flow1 and private-flow2, which are mule private flows whose processing strategy is synchronous.
The private-flow1 invokes an external service using request-response HTTP outbound endpoint.
The private-flow2 places the response from the external service on Database using Database Connector.
If there is any exception in each of the private flows, I want to handle them in the corresponding private flow itself using Catch Exception Strategy.
I have this design to separate the concerns, so that each flow performs a single responsibility.
Suppose there is an exception like IOException, SQLException or any, in any one of the private flows, how can I re-throw my custom exception, for example, org.mycompany.CustomException including the underlying cause. So main-flow will have to handle only org.mycompany.CustomException and build the related exception response.
Say for example, if private-flow1 throws org.mycompany.CustomException which is caused by IOException, the realted exception response would be:
{"exceptionMessage" : External Service unavailable, "exceptionCode" : 101}
and, if private-flow2 throws org.mycompany.CustomException which is caused by SQLException, the realted exception response would be
{"exceptionMessage" : Database unavailable, "exceptionCode" : 102}
Each private flow will have their own exception strategy and you can throw an exception using Groovy component from the flows ..
Here is a link how to do it :- How do I force an exception in mule
for custom exception create java-class which would extend DefaultMessagingExceptionStrategy
Update:-
An example to use custom-exception-strategy:- Why is Mule exception strategy so chatty?

How can I handle exception raised during Castle Windsor optional property injection?

Castle Windsor 3.2 provides a cool addition that is Diagnostic logging in the container. This helped me redirect the container logs to a log4net log file that's being used to store the application logs.
What I'd like to do now is to be able to actually catch the Exception the container detects while injecting my optional property.
In my specific situation, an Oracle database error ORA-28000: the account is locked was being raised while Castle tried to execute my code to inject the Database property in a BaseController class:
public class BaseController : Controller
{
/// <summary>
/// Repository interface injected by Castle Windsor IoC container.
/// See <see cref="MyProject.Widgets.CastleWindsor.Facilities.PersistenceFacility.Init()"/> for more information.
/// </summary>
public ILogRepository Database { get; set; }
}
This Database property is null when I'm inside an action method in an Controller that inherits from BaseController. This all happens because Castle Windsor "swallows" the exception. The only message the user gets is: Object reference not set to an instance of an object. OK but I'd like to show the real exception/reason to the user, that is, ORA-28000: the account is locked. This message gets logged by Castle Windsor thanks to the aforementioned Diagnostic logging. This is cool but I want to be able to really catch the exception inside the catch block:
public class SubCatListController : BaseController
{
public ActionResult SubCatList(string subcat)
{
try
{
var sub = Database.GetLogSubCategory(subcat);
}
catch(Exception e) // I'd like to get the real exception from Castle Windsor here...
{
Logger.Error(e.Message, e);
}
}
}
Is this scenario possible with property injection?
As Krzysztof Kozmic mentioned in his comment we should not have any code that tries to do external object initialization while injecting a property.
My problem as I describe in this subsequent comment was that I was trying to open a database connection while initializing the property.
I removed that code and now the exception is only raised in my own domain code when that injected property is used for the 1st time.
Today I hit this same problem: one thing that helped me figure out the error was to momentarily use Constructor injection instead, like this:
private OEVizion _database;
public ReportingPeriodsController(OEVizion database)
{
_database = database;
}
Doing this I was able to see what was the error: version mismatch between log4net - the one in the OEVizion class library and the one used in the .Web project.
After getting the EF context correctly initialized I got back to Property injection and I'm back in business. :D
When you have optional dependencies it is always better to use the Null Object pattern.
public BaseController() {
Database = NullLogRepository.Instance;
}
It prevent the NullReferenceException and you can provide behavior you expect (do nothing, throw specific exception, log to trace etc.)

Exception Thrown From Service Not Being Caught in Controller

In my Grails service I have code like the following:
def createCharge(chargeParams) {
try {
def charge = Charge.create(chargeParams)
} catch (CardException e) {
throw e
}
}
From my controller I do the following:
try {
service.createCharge(chargeParams)
} catch(CardException e) {
}
However, my controller is not catching the re-throwing of the CardException. If I wrap CardException in a RuntimeException via:
throw new RuntimeException(e)
and/or remove the signature from the catch to just catch(e) without typing it, it works, but I lose some information from the exception, like the message.
As a note, CardException is an Exception, not a RuntimeException. I'm not sure if that matters.
Unlike Java, you don't have to declare the (checked) exceptions that are thrown by a Groovy method, because any undeclared checked exceptions are wrapped in an UndeclaredThrowableException. So this:
def createCharge(chargeParams) {
try {
def charge = Charge.create(chargeParams)
} catch (CardException e) {
throw e
}
}
is effectively the same as:
def createCharge(chargeParams) throws UndeclaredThrowableException {
try {
def charge = Charge.create(chargeParams)
} catch (CardException e) {
throw new UndeclaredThrowableException(e)
}
}
the exception thrown by the above, obviously wouldn't be caught by:
try {
service.createCharge(chargeParams)
} catch(CardException e) {
}
But it will be caught by:
try {
service.createCharge(chargeParams)
} catch(e) {
}
Because this is just a shorthand for:
try {
service.createCharge(chargeParams)
} catch(Exception e) {
}
Unlike Java, you don't have to declare the (checked) exceptions that are thrown by a Groovy method, because any undeclared checked exceptions are wrapped in an UndeclaredThrowableException.
You seem to imply that Groovy wraps checked Exceptions by a UndeclaredThrowableException, this is not the case. If a Grails Service throws a unchecked Exception the Exception is eventually wrappped by an UndeclaredThrowableException but this is a java.lang.reflection mechanism and will only occur when a proxy class is involved.
This happens to be the case because a Grails Service is involved. I'm not sure how many proxy classes are exactly involved by there is at least one: a class that does the transaction handling (by Spring).
The class will wrap any method in the Service with a transaction and rollback the transaction when a RuntimeException occurs. Spring transaction management by default doesn't rollback in case of a checked Exception.
Java
This makes sense in plain old java, since the developer will see the Exception in the application code and will be warned to do something about it. If the developer is smart he will deal with any Exceptions during the scope of a transaction. If he doesn't rollback the transaction he is basically saying: “In this situation, the data integrity provided by the transaction is not important to me. I will recover from this error in some other way”
Groovy
This doesn't make sense in a Groovy world because the Groovy compiler doesn't enforce the dealing with Exceptions. It in effect treats Exceptions exactly the same way as RuntimeExceptions.
There is however a caveat: The reflection mechanism sees an Exception thrown by the proxy that is not in the method signature of the original Service. This is possible because:
Groovy doesn't enforce handling the Exceptions
A proxy method can always throw any Throwable (check InvocationHandler JavaDoc)
Because the reflection mechanism used is from Java, it must conform to the Java rules. So it will have to wrap the Exception in a RuntimeException,.. in this case a UndeclaredThrowableException.
Grails
Now it gets really tricky because if you call your Service method from a Controller and an Exception occurs. You will see a RuntimeException bubble up (because of some hidden mechanism) but your transaction will not be rolled back (because of some hidden mechanism).
This behaviour is very dangerous as the developer really has to remember to properly deal with any Exceptions (which the compiler will not help with) or the developer has to make sure that any Service is properly instructed with #Transactional(rollbackFor = Throwable).
This is a design issue that I think the developers of Grails have overlooked when they first designed this. But I think the default behaviour is so wrong and so dangerous this should really be changed.
I think the simple solution to the problem is to add a throws CardException statement to the service method, thus the exception will no longer be wrapped in UndeclaredThrowableException and the controller will catch the proper exception type.
Just catch the UndeclaredThrowableException, get the message from it, and then re-throw if need be.
catch (UndeclaredThrowableException e) {
def s = e.getUndeclaredThrowable().getMessage()
// do something with the message
throw e
}
The above code fragment will just catch the exception you've explicitly thrown in the code (eg CardException). For example a NullPointerException will not be caught and bubble up.

What class members do Throwable and Exception have in the D programming language?

I'm particularly interested, how I can produce nested exception and how I can access those afterwards when I handle them. A link to some documentation would be appreciated. I have already tried to find it on the D website. No success though. I'm particularly interested in D2.
Throwable documentation: http://dlang.org/phobos/object.html#Throwable
Throwable is implemented here: https://github.com/D-Programming-Language/druntime/blob/master/src/object_.d#L1304
Exception, which is currently not documented, is a subclass of Throwable with no new fields or methods.
Error, which is currently also not documented, is a subclass of Throwable with one new field: bypassedException, which is documented as following:
The first Exception which was bypassed when this Error was thrown, or null if no Exceptions were pending.