My ASP.NET Core 2.1 API app communicates with a third party API so I'm creating an ApiClient with generic CRUD methods in it.
The question is how I should handle a scenario where I got nothing from the API call -- I've seen cases where sometimes APIs return 204 but sometimes, they just return nothing at all with a status 200.
When I try to return null in case my response has nothing in it, I'm getting an error that says I can't do it because T may not be nullable.
Here's my code:
private readonly HttpClient _httpClient public MyClass(HttpClient httpClient) { _httpClient = httpClient; } public Task<T> GetMyData<T>() { try { var response = _httpClient.GetStringAsycn("https://someApiUrl"); // This is where I'm a bit stuck if(string.IsNullOrEmpty(response)) return null; // <<-- Can't return NULL! var data = JsonConvert.DeserializeObject<T>(response); return data; } catch(Exception e) { throw new Exception(e.Message); } }
Task.FromResult<T>(null).