Use GetLastError() to retrieve custom exception properties - c#

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.

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.

Catching custom exception from WCF

I have a Custom class, InvalidCodeException in Project A
public class InvalidCodeException : Exception
{
public InvalidCodeException ()
{
}
public InvalidCodeException (string message)
: base(message)
{
}
public InvalidCodeException (string message, Exception innerException)
: base(message, innerException)
{
}
}
a WCF service in Project B.
And a client in Project C.
Project A is referenced in Project B and C.
I am throwing InvalidCodeException from Project B and catching in Project C.
Problem is that when debuggin, the exception is not catching in
catch (InvalidCodeException ex)
{
Trace.WriteLine("CustomException");
throw;
}
but in
catch (Exception ex)
{ throw; }
WCF will not serialize exceptions automatically, for many reasons(e.g. client may be written in some other language than C#, and run on platform that is different from .NET).
However, WCF will serialize some exception information into FaultException objects. This basic information contains exception class name, for example. You may store some additional data inside them if you use generic FaultException type.
I.e. FaultException<FaultInfo> where FaultInfo is your class that stores additional exception data. Don't forget to add data contract serialization attributes onto class properties.
Also, you should apply FaultContract attributes on methods that are supposed to throw FaultExceptions of your kind.
[OperationContract]
[FaultContract(typeof(FaultInfo))]
void DoSomething();
That's because all exceptions are wrapped in FaultException. Catch it and look at the InnerException property
MSDN Article
The correct way to handle this is to define a FaultContract on your service operation contract:
[OperationContract]
[FaultContract(typeof(MyException))]
int MyOperation1(int x, int y);
This will allow your client to handle the exception by catching it as a generic FaultException:
try {...}
catch (FaultException<MyException> e) {...}

Getting Data That Function Had That Threw An Exception IErrorHandler

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.

How do we create OnException events on custom baseClass

we have 2 custom class (baseClass and ChildClass) the child class has inherited from the baseClass
when we get a exception on childClass, OnException event on the baseClass should be called
it'll be like MVC Controller OnException Events
We will use for logging.
In the general case it is not possible to do. The MVC OnException works because the framework catches any unhandled exceptions and forwards them to OnException. The framework code for calling a controller action is something like:
try
{
controller.SomeAction();
}
catch(Exception ex)
{
controller.OnException(ex);
}
The entire implementation depends on the caller of the code taking the responsibility to handle the exceptions. With a general calls that can be used by any code you can't make any assumptions on how the class will be called.
If we somehow can make all calls go through the base class we can make something similar:
public class Base
{
public BlahaMethod()
{
try
{
DoBlaha();
}
catch(Exception ex)
{
OnException(ex);
}
}
protected abstract void DoBlaha();
private void OnException(Exception ex)
{
// Handle exception
}
}
public class Derived
{
protected virtual void DoBlaha()
{
throw new NotImplementedException();
}
}
You can catch exception with a try-catch-finally construct. The only general exception handler (known to me) is the unhandled exception handler in the appdomain.

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