开发者

Retrieve FormatException Argument

I'm using a closed-source third-party library like this:

object val = SomeClass.ExtractValue( someObject );

Now somewhere further down the road, the third-party library tries to parse a DateTime value that has an unexpected format and throws a FormatException.

In this case, I would like to retrieve the string that it hasn't succeeded to parse and try to parse it myself. Something like this:

object val;
try
{
    val = SomeClass.ExtractValue( someObject );
}
catch( FormatException e )
{
    string failed = e.GetParseArgument( );
    val = DateTime.Parse( failed + " 2010" );
}

Yes, simply appending the year is pretty pointless, but you get the idea. The third-party library doesn't support all formats I need, but I can't easily 开发者_如何学Goget the data from "someObject" either. (Yes, I could try to replicate what the library does using Reflector, but I'd like to avoid that.)

Is there any way to do this? Thanks.


Since someObject is an IDataReader, you could create a decorator and pass that into ExtractValue. You could then intercept the date string and modify the format before it gets passed to the library e.g.

public class DateFormattingDataReader : IDataReader
{
    private readonly IDataReader inner;

    public DateFormattingDataReader(IDataReader inner)
    {
        this.inner = inner;
    }

    public string GetString(int index)
    {
        string s = this.inner.GetString(index);
        if(index == problematicColumnIndex)
        {
            //try to parse string and then format it for the library
        }
        else return s;
    }
}

Alternatively you could record all values read from the reader, then you can get the failing data as the last read item and try to parse it yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜