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?
Presuming you want to do something if the exception is thrown I'd reccomend you do something more like this:
Where
MyExceptionlooks like this:and the calling code looks like this:
This way the calling code is aware that an exception is thrown (no hidden functionality here) but you can also handle that exception in an elegant way. You can extend
MyExceptionif you need to provide more information for your handling logic.