I can’t handle exceptions in the Controller on an ASP.NET API

Asked

Viewed 41 times

0

In the code below I am trying to change the status of the request when I could not find the Project ID.

        // GET api/values/5
        [HttpGet("{id}")]
        public Project Get(int id)
        {
            try
            {
                var project = _acess.GetProject(id);
                return project;
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.InnerException.Message);
                
            }

        }

However, I come across the following error message: CS0029: Cannot implicitly convert type "Microsoft.AspNetCore.MVC.Objectresult" to "SS_API.Model.Project"

I also need to return the exceptions of void type functions, but also do not know how to implement a code that worked. Follows code below:

    public void Put([FromBody] Project project)
    {

        try
        {
            _acess.UpdateProject(project);
        }
        catch(DataException ex)
        {
          //Retorno do status do erro.
        }
      
    }

I beg someone to help me.

1 answer

0

The GET method does not work because in your signature it was placed that it should return a Project (public Project Get(int id)) and that’s not what happens when an exception is made, you can change the return methods forever to return an Ihttpactionresult or an Actionresult, something like:

public IHttpActionResult Get(int id) or public ActionResult Get(int id)

this allows you to return status instead of objects, for example, when a request has been successful you use a

    [HttpGet("{id}")]
    public ActionResult<Project> Get(int id)
    {
        try
        {
            var project = _acess.GetProject(id);
            return OK(project);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

Being ok the status 200, when an error is returned by part of data that the user reported or something related, you would return a

return BadRequest("campo tal invalido");

The same would work for your put method, doing the operation that needs to be done and returning an ok at the end indicating that everything that should be done was done.

public ActionResult Put([FromBody] Project project)
{
    try
    {
        _acess.UpdateProject(project);
    }
    catch(DataException ex)
    {
        return BadRequest(ex.Message);
    }
     
    return Ok();
}
    
  • I cannot use the Get method without declaring the Project type signature function, so I am only able to use Actionresult in functions that I receive Project as a parameter. Your solution worked for me in the Put function, but not in the Get function. It would have some hint of what to do?

  • Why can’t you use it? can you post the error message? is used return Ok(project) ?

  • This way, my Get gives me nothing: public Actionresult Get(int id) { Try { var project = _acess.Getproject(id); } catch (Dataexception ex) { Return Badrequest(ex.Message); } Return Ok(project); }

  • Otherwise: public Actionresult Get(int id) { Try { var project = _acess.Getproject(id); Return project; } catch (Dataex exception) { Return Badrequest(ex.Message); } Return Ok(); } Error CS0029 Cannot implicitly convert type "SS_API.Model.Project" to "Microsoft.AspNetCore.Mvc.Actionresult"

  • @Tester Try again the first informed method only instead of just ActionResult, utilize ActionResult<Project>, so we have explicitly defined that it will return a project. Alias nothing prevents you from giving the ok Return up there inside the Try where it was being done previously, in fact it needs to be like this, the project variable is only set inside the Try block, maybe that’s why nothing is being returned, the strange thing is that you should be having a compilation error with the code like this.

  • @Tester would be interesting to know also how is consuming this controller

  • @Tester updated the answer to better visualize how your GET method should look

  • public Actionresult<Project> Get(int id) { Try { var project = _acess.Getproject(id); Return project; } catch (Dataexception ex) { Badrequest(ex.Message); } Return Ok(); } .

  • public Actionresult<bool> Delete(int id) { bool aux = false; _acess.Getproject(id); Try { //Project project project = _acess.Getproject(id); _acess.Deleteproject(id); _acess. Save(); aux = true; } catch (Dataexception ex) { Badrequest(ex.Message); aux = false; } Return aux; } Can you help me with what’s wrong with this one? It is possible in bool?

Show 4 more comments

Browser other questions tagged

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