I have an ASP.NET Core API app and I'm using IActionResult
for a return type. For an example, I'll use the following snippet from Microsoft's documentation:
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetById(int id)
{
if (!_repository.TryGetProduct(id, out var product))
{
return NotFound();
}
return Ok(product);
}
My controllers are similar, where routes are using the IActionResult
and using functions such as NotFound()
, BadRequest()
, or Ok()
and following the repository pattern for obtaining data from a database. In Microsoft's trivial example, they're simply evaluating if the result is null
, and if it is they'll return NotFound()
.
In the repository logic, there could be any number of issues that occurred. For example:
- DB query success, but product wasn't found (404 not found)
- DB query failure, connection string was invalid (500 server error)
- Product ID didn't pass some validation test (400 bad request)
In all of the above cases, you could maybe justify returning null
from the TryGetProduct()
function, since it wasn't able to retrieve a product in any of those cases. But returning null
as a general return result from a repository function doesn't seem helpful and could mean any number of issues occurred. What's the best way I can return data from a repository to allow the controller to then determine the appropriate status code to return and what are the best practices for this?