5.29Exception Suppression Mechanism (Silent Handling)
When initiating an HTTP remote request, the following exceptions may be encountered:
- The target host is unreachable
- The request is canceled
- The request times out
- Other network exceptions
By default, these exceptions interrupt program execution. Although developers typically use try/catch for exception handling, in certain scenarios we would rather silently return null when an exception occurs without interrupting the flow. To this end, the framework provides flexible exception suppression.
HTTP declarative requests suppress exceptions through the SuppressExceptionsAttribute attribute. The corresponding HTTP declarative extractor is implemented as the SuppressExceptionsDeclarativeExtractor type, which is responsible for parsing the SuppressExceptionsAttribute attribute and building the exception suppression configuration required by an HttpRequestBuilder instance.
// Applied on the interface definition, affecting all methods[SuppressExceptions] // Suppress all exceptionspublic interface IHttpService : IHttpDeclarative{ [Get("https://furion.net/logo.png")] Task<string> GetStringAsync(); // Applied on the method [SuppressExceptions(typeof(TimeoutException), typeof(TaskCanceledException))] // Suppress timeout and cancellation exceptions [Get("https://furion.net/logo2.png")] Task<string> GetStringAsync(); [SuppressExceptions(false)] // Disable exception suppression (restore the default configuration) [Get("https://furion.net/logo2.png")] Task<string> GetStringAsync();}After it is enabled, the exception suppression mechanism is automatically set when an HTTP remote request is sent.
SuppressExceptionsAttribute includes the following constructors and properties:
-
Constructors:
new(): Applies to a method or interface; suppresses all exceptions.new(enable): Applies to a method or interface; indicates whether to enable exception suppression.new(types): Applies to a method or interface; suppresses exceptions of the specified types.
-
Properties:
Types: The collection of exception suppression types (of typetype[]; every element in the array must be of typeSystem.Exceptionor a derived type).