Globally configure custom exception type for IApiResponse? #2082
-
|
Hi, Our backend returns a response body when an exception occurs, this is similar to the problemdetail, but still quite different. Now I was wondering if I can somehow configure IApiResponse to return that as response.Error type in a global context, instead of having to use .GetContentAsync everwhere an error could occur? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
There is no setting that swaps IApiResponse.Error to a custom type globally. Error is an ApiExceptionBase (ApiException for response errors), so the strongly typed body is not surfaced there directly. But you have two clean global options:
if (response.Error is ApiException apiEx && apiEx.HasContent)
{
var myError = await apiEx.GetContentAsAsync<MyErrorBody>();
}
public sealed class MyApiException : ApiException
{
private MyApiException(ApiException inner)
: base(inner.RequestMessage, inner.HttpMethod, inner.Content, inner.StatusCode,
inner.ReasonPhrase, inner.Headers, inner.RefitSettings!) { }
public MyError? Error { get; private set; }
public static async Task<MyApiException> CreateAsync(ApiException inner)
{
var ex = new MyApiException(inner);
if (inner.HasContent)
ex.Error = await inner.GetContentAsAsync<MyError>();
return ex;
}
}
var settings = new RefitSettings
{
ExceptionFactory = async response =>
{
if (response.IsSuccessStatusCode) return null;
var apiEx = await ApiException.Create(
response.RequestMessage!, response.RequestMessage!.Method, response, settings);
return await MyApiException.CreateAsync(apiEx);
}
};Register that settings instance once (AddRefitClient(settings) / RestService.For(client, settings)) and the typed error flows into response.Error for every call. Cast response.Error to MyApiException to read .Error. Recommendation: option 2 if you want it globally typed; option 1 if you just want to avoid repeating GetContentAsync at call sites. |
Beta Was this translation helpful? Give feedback.
There is no setting that swaps IApiResponse.Error to a custom type globally. Error is an ApiExceptionBase (ApiException for response errors), so the strongly typed body is not surfaced there directly. But you have two clean global options:
ApiException exposes GetContentAsAsync(), so you do not need GetContentAsync everywhere: