I have a generic APIResponse<T> object that wraps the result of an API call:
public class APIError
{
public string ErrorMessage { get; set; }
}
public class APIResponse<T>
{
public T Result { get; set; }
public APIError Error { get; set; }
public bool HasError
{
get { return Error != null; }
}
}
I have a method that calls an API:
public APIResponse<string> GetUserName()
{
APIResponse<string> response = new APIResponse<string>();
try
{
// make http request
response.Result = httpResponse;
}
catch
{
response.Error = new APIError { ErrorMessage = "Some error occurred" };
}
return response;
}
// I call the method like this
APIResponse<string> userNameResponse = GetUserName();
// i need to handle the apiResponse
HandleAPIResponse(userNameResponse);
I want to create a generic method that inspects the APIResponse<T> object, and throws an exception if it has an error, but i can't make it work without specifying the result type:
public void HandleAPIResponse(APIResponse<T> apiResponse)
{
if (apiResponse.HasError)
throw new Exception(apiResponse.Error.ErrorMessage);
}
Can i make a method that accepts APIResponse<T> as parameter, but without specifying the type of T?
The method definition should be as follows:
public void HandleAPIResponse<T>(APIResponse<T> apiResponse)
{
if (apiResponse.HasError)
throw new Exception(apiResponse.Error.ErrorMessage);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With