Skip to content

Fine Grained HTTP Exceptions Handling

fonlow edited this page Feb 12, 2021 · 3 revisions

System.Net.Http.HttpRequestException had offered limited info upon HTTP request errors. To provide fine grained error handling, the following code block expose more info for client codes to handle.

using System;

namespace Fonlow.Net.Http
{
	using System.Net.Http;

	public class WebApiRequestException : HttpRequestException
	{
		public System.Net.HttpStatusCode StatusCode { get; private set; }

		public string Response { get; private set; }

		public System.Net.Http.Headers.HttpResponseHeaders Headers { get; private set; }

		public System.Net.Http.Headers.MediaTypeHeaderValue ContentType { get; private set; }

		public WebApiRequestException(string message, System.Net.HttpStatusCode statusCode, string response, System.Net.Http.Headers.HttpResponseHeaders headers, System.Net.Http.Headers.MediaTypeHeaderValue contentType) : base(message)
		{
			StatusCode = statusCode;
			Response = response;
			Headers = headers;
			ContentType = contentType;
		}
	}

	public static class ResponseMessageExtensions
	{
		public static void EnsureSuccessStatusCodeEx(this HttpResponseMessage responseMessage)
		{
			if (!responseMessage.IsSuccessStatusCode)
			{
				var responseText = responseMessage.Content.ReadAsStringAsync().Result;
				var contentType = responseMessage.Content.Headers.ContentType;
				throw new WebApiRequestException(responseMessage.ReasonPhrase, responseMessage.StatusCode, responseText, responseMessage.Headers, contentType);
			}
		}
	}
}

If in codegen.json "UseEnsureSuccessStatusCodeEx": true is included, the generated codes will include this code block at the end, which is used throughout the generated codes.

If your applications uses generated codes in a few CS files generated by OpenApiClientGen or WebApiClientGen, you may want them to share the code block, otherwise, the compiler will complicate duplicate codes. Then you may include this setting:

"IncludeEnsureSuccessStatusCodeExBlock": false

Thus the generated codes won't include the code block.

If generated files stay in the same assembly, you should put the code block to a CS file in the same assembly.

If generated files stay in multiple assemblies, you should put the code block to a standalone assembly for example "fonlow.net.http.dll", which is referenced in these assemblies.

Clone this wiki locally