Exception handlers are only supported for BER decoding. BER is more amenable to error recovery than some other encoding rules.
To implement an exception handler, you do two things:
Implement the Asn1BerExceptionHandler
interface. In the
example below, you can see the signature of the only method in this
interface.
Instantiate an instance of your exception handler class
and set it as the exception handler, using
Asn1BerDecodeBuffer.SetExceptionHandler()
.
The following example is taken from the reader program of the
csharp/sample_ber/ErrorHandler
sample. In that sample,
we illustrate ignoring all of the exceptions that can be ignored.
You can see that some exceptions requuire skipping a TLV
(tag-length-value), while others don't require any special action.
The runtime documentation for
Asn1BerExceptionHandler
documents what is required
to handle each type of exception. Exceptions that are not ignored are
simply returned by the handler; if we had wanted to, the handler
could have constructed some other exception and returned that, instead.
public class Handler : Asn1BerExceptionHandler { public System.Exception HandleException(Asn1Exception e, Asn1BerDecodeBuffer buffer) { try { if (e is Asn1MissingRequiredException || e is Asn1InvalidEnumException) { //ignore exception; no recovery action required System.Console.Out.WriteLine("IGNORED: " + e.Message); return null; } else if (e is Asn1SeqOrderException || e is Asn1UnexpectedElementException || e is Asn1SetDuplicateException || e is Asn1NotInSetException || e is Asn1InvalidChoiceOptionException) { //skip the offending element buffer.SkipTLV(); System.Console.Out.WriteLine("IGNORED: " + e.Message); return null; } } catch (System.Exception) { //ignore: recovery failed } return e; } }
Setting the exception handler is simple:
// Create a decode buffer object Asn1BerDecodeBuffer decodeBuffer = new Asn1BerDecodeBuffer (ins); decodeBuffer.SetExceptionHandler(new Handler());