Getting Data That Function Had That Threw An Exception IErrorHandler - c#

I am using IErrorHandler to catch ApplicationExceptions.
The HandleError method of IErrorHandler accepts an Exception as input.
I am throwing customExceptions in my code if user data is invalid. HandleError is catching them just fine.
My question is: Is there a way to attach/or get the input data the method was using where the Exception took place and attach that data somehow to the method? Or add another parameter to the constructor of my customException that can hold the input data to the method?
//sample constructor to customExceptio
public AddressException(string message): base(message)
{
}
If I add another parameter string InputData..
1. How do I do that?
2. How do I get the InputData data out of the customException on the HandleError side?
public bool HandleError(Exception error)

Should/Could be something like this.
public class AddressException : Exception
{
public string InputData { get; set; }
public AddressException(string message, string inputData) : base(message)
{
InputData = inputData;
}
}
Then you can just access whatever data you passed to the contructor when you handle the Exception.

Related

C# user defined exception

Is it necessary to declare a class in 'public ' visibility mode if the class is defining the user defined exception which extends System.exception class in C#?
It entirely dependes on how you want to use your user defined exception class.
The concept of access modifier is not related at all with the idea of a user defined exception.
A user defined exception is just a user defined class which extends System.Exception, while an access modifier is a construct which specifies the visibility of that class with respect to the client code.
This means that if you just want to use your custom exception class inside the defining assembly you can simply define it as an internal class.
Of course this won't be very useful, because you usually define custom exception class inside class libraries and you want them to be visible in any assembly referencing your class library, so that a consumer can have a chance to handle your custom exception class if it makes sense in his or hers client code.
Try it on DotNetFiddle and see:
public class Foo
{
private class MyException : Exception
{
public MyException(string message) : base(message) { }
}
public static void Throw()
{
throw new MyException("Hello world.");
}
}
public class Program
{
public static void Main()
{
try
{
Foo.Throw();
}
//catch(Foo.MyException myException)
//{
// This doesn't compile
//}
catch(System.Exception exception)
{
Console.WriteLine
(
"Exception is of type '{0}' with a message of '{1}'",
exception.GetType().Name,
exception.Message
);
//Does not compile:
//var typedException = (Foo.MyException)exception;
}
}
}
Output:
Exception is of type 'MyException' with a message of 'Hello world.'
So it turns out you can still catch the exception, inspect its type, and read its base properties, and everything works. But if you want to handle it in a type-safe way and cast it to the specific type, your code won't compile. This also means you can't use a type-specific catch handler.

Get exception from Facade constructor when resolving controller

I have simple controller with one dependency
public TestController(ITestFacade testFacade)
{
_testFacade = testFacade;
}
and simple facade
public class TestFacade : ITestFacade
{
public TestFacade()
{
throw new Exception("Test");
}
}
I have Unity resolver and registration
public static void RegisterDependencies(IUnityContainer container)
{
container.RegisterType<ITestFacade, TestFacade>();
}
UnityResolver is common as found everywhere. Nothing custom.
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
// Here in one of Inner Exceptions is my Facade exception, but I want to get it later
return null;
}
}
Please consider this as test scenario. Facade in constructor should fail for any reason. It is not important now.
Running application results in exception:
An error occurred when trying to create a controller of type 'TestController'. Make sure that the controller has a parameterless public constructor.
Ok, this is because of error in constructor of Facade when resolver is not able to get instance and activator in controller failed.
My question is - is there any way how to catch this exception in IHttpControllerActivator or somewhere?
I can try catch code in Facade constructor and log it somehow, but why this exception is ignored after resolver.

Use GetLastError() to retrieve custom exception properties

So I've created a custom exception class (let's call it CustomException) along with some custom properties not found in the Exception class. In the global.asax.cs file there is the Application_Error method that is called whenever an exception happens. I'm using Server.GetLastError() to grab the exception that triggered the Application_Error method. The problem is that Server.GetLastError() only grabs an Exception object and not the CustomException object that is being thrown along with its custom properties. Basically the CustomException is stripped down to an Exception object when retrieved by Server.GetLastError(), thus losing the custom properties associated with CustomException.
Is there a way for GetLastError() to actually retrieve the CustomException object and not the stripped down Exception version? This is needed in order to store the errors in a database table with more information than would normally be supplied by an Exception.
Application_Error:
protected void Application_Error(object sender, EventArgs e)
{
// This var is Exception, would like it to be CustomException
var ex = Server.GetLastError();
// Logging unhandled exceptions into the database
SystemErrorController.Insert(ex);
string message = ex.ToFormattedString(Request.Url.PathAndQuery);
TraceUtil.WriteError(message);
}
CustomException:
public abstract class CustomException : System.Exception
{
#region Lifecycle
public CustomException ()
: base("This is a custom Exception.")
{
}
public CustomException (string message)
: base(message)
{
}
public CustomException (string message, Exception ex)
: base(message, ex)
{
}
#endregion
#region Properties
// Would like to use these properties in the Insert method
public string ExceptionCode { get; set; }
public string SourceType { get; set; }
public string SourceDetail { get; set; }
public string SystemErrorId { get; set; }
#endregion
}
Just cast the Server.GetLastError's result to CustomException:
var ex = Server.GetLastError() as CustomException;
Remember that in some situations your CustomException could not be the top exception in the StackTrace, in this case you'll need to navigate through the InnerExceptions to find the right one.
Please, check the #scott-chamberlain links about how to design custom exceptions.

Resolution of the dependency failed-I/O Exception

I am calling a method GetData from a class DataProvider, where the method is implemented as a interface. Calling is done as:
Response = ObjectRegistry.Instance.Resolve<IDataProvider>().GetData(id).
Structure of the interface looks like.
namespace A.B.C.D
{
///<Summary>
/// Gets the answer
///</Summary>
public interface IDataProvider
{
GetDataInfo GetData(int id);
}
}
and my DataProvider class looks like.
namespace A.B.C.D
{
public class DataProvider : IDataProvider
{
public GetDataInfo GetData(int id)
{
GetDataInfo DataInfo = new GetDataInfo();
//return obj;
return DataInfo;
}
}
}
But when I am trying to execute this I am getting following error:
Message: Resolution of the dependency failed, type = ".DataInfo.IDataProvider", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, DataInfo.IDataProvider, is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:
Resolving DataInfo.IDataProvider,(none)
Tried searching in almost all the SO posts, but couldn't find any helpful suggestion

Handle base class exception

I have a following C# scenario-
I have to handle an exception in base class that actually occurs in the derived class.
My base class looks like this:
public interface A
{
void RunA();
}
public class Base
{
public static void RunBase(A a)
{
try
{
a.RunA();
}
catch { }
}
}
The derived class is as follows:
public class B: A
{
public void RunA()
{
try
{
//statement: exception may occur here
}
catch{}
}
}
I want to handle the exception, lets say exception C, that occurs in B(at //statement above).
The exception handling part should be written in base class catch inside RunBase. How can this be done?
public class Base
{
public static void RunBase(A a)
{
try
{
a.RunA();
}
catch(SomeSpecialTypeOfException ex)
{
// Do exception handling here
}
}
}
public class B: A
{
public void RunA()
{
//statement: exception may occur here
...
// Don't use a try-catch block here. The exception
// will automatically "bubble up" to RunBase (or any other
// method that is calling RunA).
}
}
How can this be done?
What do you mean? Just remove the try-catch block from RunA.
Having said that, you need to make sure Class A knows how to handle the exception, this includes streamlining it to UI, logging, ... This is in fact rare for a base class. Handling exception normally happen at the UI level.
public class B: A
{
public void RunA()
{
try
{
// statement: exception may occur here
}
catch(Exception ex)
{
// Do whatever you want to do here if you have to do specific stuff
// when an exception occurs here
...
// Then rethrow it with additional info : it will be processed by the Base class
throw new ApplicationException("My info", ex);
}
}
}
You also might want to throw the exception as it is (use throw alone).
If you dont need to process anything here, dont put try{} catch{}, let the exception bubble up by itself and be processed by the Base class.
Just remove the try catch from class B, if the exception occurs it will propergate up the call chain until it is handled. In this case you can handle the exception in RunBase using your existing try catch block.
Though in your example B isn't derived from your base class Base. If you really want to handle a situation where an exception is thrown in a derived class in its parent you could try something like:
public class A
{
//Public version used by calling code.
public void SomeMethod()
{
try
{
protectedMethod();
}
catch (SomeException exc)
{
//handle the exception.
}
}
//Derived classes can override this version, any exception thrown can be handled in SomeMethod.
protected virtual void protectedMethod()
{
}
}
public class B : A
{
protected override void protectedMethod()
{
//Throw your exception here.
}
}

Categories

Resources