I'm calling API in one of my Service classes as below:
public GetCustomerApiResponse SearchCustomerByEmail(string email)
{
GetCustomerApiResponse customerApiResponse = null;
try
{
var requestBody = JsonConvert.SerializeObject(new
{
content = $@"{{""Email"":""{email}""}}",
key = _apiEnvironment,
name = "search-customer"
});
var content = new StringContent(requestBody, Encoding.UTF8, "application/json");
var res = _client.PostAsync(_baseUrl, content).Result.Content.ReadAsStringAsync().Result;
customerApiResponse = JsonConvert.DeserializeObject<GetCustomerApiResponse>(res);
}
catch
{
// ignored
}
return customerApiResponse;
}
Here, I'm returning Deserialized data of type GetCustomerApiResponse
. I want to return Different Response Type in catch (say e.g. of type GetCustomerApiResponseError
). How to achieve this?
I'd use a class
CustomerApiResult
which has a propertyGetCustomerApiResponse
and alsoValidResponse
+IEnumerable<string> ResponseErrors
.Now you can use it in this way:
So i don't return the converted object but an API-Result object that contains the object(or null) and has a
ValidResponse
property that you should check before.So for example:
One of the advantages of this approach is that you can use the logic even if there are no exceptions raised(so for example there is an invalid result from the api or a logical flaw). Another advantage is that you can use it with multiple consecutive calls in the API before you return to the upper application layers and collect the response-errors(for example to log them separately). You can also use this to decide if you can continue with the next step if there is already an invalid reponse in the last call or if that call was not important enough to stop the whole workflow.