How to return error message with API

Asked

Viewed 140 times

-1

Good morning, I’m trying to return error message when something goes wrong in the api, I’ve done it for all the request of the api, but for one specific error, the action that shows all users that is IEnumerable.

here is my code;

    [HttpGet]
    public IEnumerable<User> GetAll()
    {
        try
        {
            return userRepository.GetAll();
        }
        catch (Exception ex)
        {
            return StatusCode(500,ex.InnerException.Message);
        }

    }

How do I return the error? mine return StatusCode(500,ex.InnerException.Message); gives the following error

Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.ObjectResult' to 'System.Collections.Generic.IEnumerable<API.Models.User>'. An explicit conversion exists (are you missing a cast?) [API]

2 answers

2

Change the method signature to return one IActionResult and put your user feedback within the method OK.

[HttpGet]
public IActionResult GetAll()
{
    try
    {
        return Ok(userRepository.GetAll());
    }
    catch (Exception ex)
    {
        return StatusCode(500, ex.InnerException.Message);
    }
}

0


To solve your problem just change the return on the signature to ActionResult<IEnumerable<User>>. Other amendments no longer needed.

It should be noted that this option is only available from version 2.1.

    [HttpGet]
    public ActionResult<IEnumerable<User>> GetAll()
    {
        try
        {
            return userRepository.GetAll();
        }
        catch (Exception ex)
        {
            return StatusCode(500,ex.InnerException.Message);
        }

    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.