Returning error string from MVC6/WepApi controller

Viewed 10707

The template WebApi controller in MVC6/WebApi implements an action that returns a collection for the Get method like this:

[HttpGet]
public IEnumerable<MyEntity> Get()
{
    //my code to return entities
}

Assuming that my code to return the result throws an exception, how would I return an error message to the consumer?

As far as I noticed an exception would result in HTTP 500. This is fine but I would like to give the caller a message telling him what went wrong. Because of the signature of the template action I can not catch the exception and return some Http*** or ObjectResult instance.

5 Answers

Migth be little bit late to anserw but now the best way to get a custom error with a custom code seems to be using StatusCode method.

` [HttpGet("{id}")]
[ProducesResponseType(typeof(IEnumerable<string>), 200)]
[ProducesResponseType(typeof(void), 404)]
public IActionResult Get(int id)
{
    Product product = null;
    if (!this.productRepository.TryGet(id, out product))
    {
        return StatsusCode(500, "NotFound");
    }

    return Ok(product);
}`
Related