User defined exception: Exception vs ApplicationException - exception

I want to implement user defined exception in my project. And I got so many articles in internet.
I have to create a custom class and that will be inherit from Exception class.
Ex: public class EmployeeListNotFoundException: Exception{ }
I got so many articles who are saying custom class should inherit from ApplicationException class.
But according to msdn site it will be inherit from Exception class. See link
[Userdefined exception][1].
Then what should I use ApplicationException or Exception class?
Thank you.

Before the release of .NET 3.0, Microsoft advised to derive custom exceptions from the ApplicationException class. However, it was found that this practice did not add any value, so the current recommendation is to derive custom exceptions from the Exception class.

Related

Where is System.Diagnostics.Debug.Listeners property in netstandard 2?

The ms doc says it should exist a Listeners property in Debug.Diagnostics.Debug in netstandard 2, but this is not the case in a real project. The Listeners property is undefined.
I tryed adding the System.Diagnostics.Debug nuget with no luck.
Any clue?
When you try to navigate to the page for Debug.Listeners Property for .NET Standard 2 the page clearly states:
The requested page is not available for .NET Standard 2.0. You have been redirected to the newest product version this page is available for.
Diving in a bit deeper, you can find all APIs implemented in .NET standard 2 on their github. Here you can see that the public static class Debug doesn't have a Listeners property.
However, the article on the Debug.Listeners Property I referred to above also states
The Listeners collection is shared by both the Debug and the Trace classes; adding a trace listener to either class adds the listener to both.
The .NET standard API's also learns us that the public sealed class Trace does implement public static TraceListenerCollection Listeners { get; }. This would lead me to believe you can access the Listeners through the Trace class.

How to hook interceptor for ILogger

I'm using the LoggingFacility, and need to add interceptor for the ILogger instances, created by the facility.
So far I tried to modify the component model for ILogger, and this didn't work, as the loggers are not really resolved using the standard resolving mechanism (they are created by a factory, which use some wrappers).
I was thinking to override the logging subresolver, but kernel.Resolver does not allow replacing (or wrapping) the resolver added by the facility.
I was thinking about hooking to Kernel.DependencyResolving, but it appears I can not replace the dependency there.
What is the most appropriate place to put such a hook, so I can add Interceptor for the ILogger.
EDIT: After a lot of poking around, I came with somewhat "hackish" solution, which unfortunately depends on small reflection usage.
The real problem appears to be, that the way the loggers are constructed does not follow (for me) the castle spirit of doing things. I.e. the resolver does not use the already registered logger factory, so it's impossible to add interceptors to the factory itself.
There is a great article about that on CodeProject: Aspect Oriented Programming (AOP) in C# using Castle DynamicProxy from Linjith Kunnon. It shows you how to define a Interceptor
public class LoggingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var methodName = invocation.Method.Name;
try
{
Console.WriteLine(string.Format("Entered Method:{0}, Arguments: {1}", methodName, string.Join(",", invocation.Arguments)));
invocation.Proceed();
Console.WriteLine(string.Format("Sucessfully executed method:{0}", methodName));
}
catch (Exception e)
{
Console.WriteLine(string.Format("Method:{0}, Exception:{1}", methodName, e.Message));
throw;
}
finally
{
Console.WriteLine(string.Format("Exiting Method:{0}", methodName));
}
}
}
And how to register it with Castle.Windsor
kernel.Register(
Component.For<LoggingInterceptor>()
.ImplementedBy<LoggingInterceptor>()
);
kernel.Register(
Component.For<IRocket>()
.ImplementedBy<Rocket>()
.Interceptors(InterceptorReference.ForType<LoggingInterceptor>()).Anywhere
);
Please note that there is more valuable content in the linked article and that the whole code provided here is from the article and not from me. All kudos goes to Linjith Kunnon.
You need to create your own logger factory (derived from default implementation matching your logging framework) and then you can setup facility to use this factory like this:
container.AddFacility<LoggingFacility>(f => f.UseLog4Net().LogUsing<MyFactory>());
See full example here

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

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) { }
}

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.)

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.