v1n1akabozo
v1n1akabozo

Reputation: 255

Does anyone store the data when one exception is thrown?

A few times the stack trace is not enough to track down as fast as i want an error, and it'd be very helpful if i could have the exact same data that caused the exception in first place. So i was wondering if it's ok to serialize the data into JSON and store it in the database along with the other info we already store. I've been looking around but haven't even found a single topic over this matter so i don't know if it's a good idea or a really bad one.

I'm aware that by simply reading the code i'm able to find flaws but debugging it with the problematic data imo tends to be faster.

Upvotes: -1

Views: 67

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

Yes, you have two options normally.

First, exceptions have a .Data property for adding custom user data. You can add the data that caused the exception and then serialize the exception to the database. Be sure to just use throw; not throw ex; to "bubble up" your exception after you add your state data, if you don't you will destroy the stack trace of the original exception.

public class MyClass
{
    public int Divide(int a, int b)
    {
        try
        {
            return a / b;
        }
        catch (Exception ex)
        {
            var aName = String.Join(".", typeof(MyClass).FullName, nameof(Divide), nameof(a));
            ex.Data[aName] = a;
            var bName = String.Join(".", typeof(MyClass).FullName, nameof(Divide), nameof(b));
            ex.Data[bName] = b;
            throw; //NOT throw ex;
        }
    }
}

Second, you could make a user-defined exception for the specific case and include the data that causes the exception as properties of the class.

public int Divide(int a, int b)
{
    try
    {
        return a / b;
    }
    catch (Exception ex)
    {
        throw new MyLoggedException(a, b, ex);
    }
}

Upvotes: 5

dreamerkumar
dreamerkumar

Reputation: 1550

My biggest concern would be with respect to the privacy of data. Users trust us that their information is stored securely. Typically, there are measures in place to restrict the data access from the database. But if data is stored separately in a different place, you would need to make sure that same access restrictions are in place for the log traces.

However, if privacy is not a concern, I don't see any other reason why this can be a bad idea. Except for the increased size of your logs.

Upvotes: 3

Related Questions