3.61Exception Suppression Mechanism (Silent Handling)
When initiating an HTTP remote request, you may encounter the following exceptions:
- 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 usually use try/catch for exception handling, in some scenarios we prefer that exceptions silently return null without interrupting the flow. To that end, the framework provides flexible exception suppression functionality.
- Suppress all request exceptions
var httpResponseMessage = httpRemoteService.SendAsync(HttpRequestBuilder.Post("https://furion.net/") .SuppressExceptions()); // Suppress all exceptionsWhen an exception occurs during the request, execution is not interrupted; instead null is returned, i.e. the value of httpResponseMessage is null.
In some scenarios, while suppressing exceptions, we still want to capture the exception information (for example, to write it to a log) without interrupting the normal execution of the program. In this case, you can use the SetOnRequestFailed callback:
HttpRequestBuilder.Post("https://furion.net/") .SuppressExceptions() .SetOnRequestFailed((exception, responseMessage) => // Note: responseMessage may be null { Console.WriteLine(exception.Message); });This method allows you to safely handle error information after an exception has been suppressed, and is suitable for log recording, monitoring, or other error response logic.
- Suppress only specific types of exceptions
The framework also supports suppressing only specific types of exceptions. For example, you can suppress only timeout exceptions and request cancellation exceptions:
var httpResponseMessage = httpRemoteService.SendAsync(HttpRequestBuilder.Post("https://furion.net/") .SuppressExceptions([typeof(TimeoutException), typeof(TaskCanceledException)])); // Suppress timeout and cancellation exceptions- Disable exception suppression configuration
To restore the default behavior (i.e. interrupt the program when an exception occurs), you can explicitly disable exception suppression:
var httpResponseMessage = httpRemoteService.SendAsync(HttpRequestBuilder.Post("https://furion.net/") .SuppressExceptions(false); // Restore default configurationThis configuration is equivalent to not calling SuppressExceptions(); when any exception occurs, program execution will be interrupted.