How can I return different types of HttpStatus codes in a method which returns a list?
If the method hits try
block it should return 200(Automatically it happens since it is a successful response). Need to return 404 if it hits the catch
block.
[HttpGet]
[Route("{customerId}")]
public async Task<List<CategoryEntity>> GetCategoryByCustomerId(Guid customerId)
{
try
{
List<CategoryEntity> categoryEntities = _categoryRepository.GetAllCategoriesByCustomerId(customerId);
return categoryEntities;
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return null;
}
}
If you want your method to produce specific HTTP status codes, your method should return an IActionResult
. The ActionResult
types are representative of HTTP status codes (ref).
For your method, you would return an OkResult
inside of your try block to have the method respond with an HTTP 200 and a NotFoundResult
inside of your catch for it to respond with an HTTP 404.
You can pass the data that you want to send back to the client (i.e. your List<T>
) to OkResults
's constructor.