Handling exceptions in a class library enveloping a device driver
I am writing a class library that envelopes an USB device driver. This device has its own class library, provided by the hardware vendor.
Very often, especially if you handle with old DLL or COM assemblies, there are methods (functions to be开发者_开发知识库 correct) that return TRUE if all was OK, or FALSE if any error happen. Often these methods return information about the error in one of their parameters or separately in a GetLastError method or even if in an OnError event.
Now, normally I handle all native .NET exceptions in my class libray handling locally or re-throwing to the client if the error is useful to know. But what to do with all other errors that are hidden in the vendor's methods? (in the true I have no exceptions, but only returned TRUE or FALSE values).
Let's make an example with the method "CONNECT" that connect the client to the USB device.
I envelope the method in this way:
Public Sub Connect()
oVendorDevice.connect()
End Sub
now if any connection error happen, the vendor's connect method return FALSE. But I do not know why the connection failed. To know why the connection failed I have to call (for example) the method GetLastError that gives me information about the error. (but do not forget that other vendors use other strategies like returning the error in a method's parameter or in a OnError events.
Now, in order to follow a good .NET exception handling strategy I could write something like this:
Public Sub Connect()
Dim res As Boolean = oVendorDevice.connect()
If res = False Then
Dim sError As String = oVendorDevice.GetLastError
Throw New Exception(sError) 'or a my own exception class
End If
End Sub
But I could also preserve the vendor strategy with something like
Public Function Connect2(ByRef Err As String) As Boolean
Connect2 = oVendorDevice.connect()
Err = oVendorDevice.GetLastError
End Function
or like this
Public Function Connect3() As Boolean
Connect3 = oVendorDevice.connect()
MyGetLastError = oVendorDevice.GetLastError
End Function
What is the best .NET-way to "envelope the errors" of the vendor class library?
The way I would approach this would be "as a consumer of the API, do I want to get an exception here or should this be some sort of less exceptional error case?"
In case of connection, I would generally say that probably should throw an exception -- preferably a strongly, distinctly typed one that includes the vendors error information.
Now, for a counter-example, let's say the device had an error when reading from an empty buffer. But in your program, you think it makes more sense to just return an empty buffer. This sort of case is where you probably don't need to throw an exception in your client.
精彩评论