Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle "Not Found" error in Web API Controller - Get Method, MVC 4?

I have this API method:

    [HttpGet]
    public MyTable GetMyTable(byte id, string langid)
    {
        MyTable mytable = db.MyTables.Find(id, langid);

        if (mytable  == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }

        return mytable;
    }

Currently it throws NotFound exception, but I don't want it to throw exception, instead I want to get in JSON format message that the required entry it was not found.

I could add try/catch block with HttpResponseException but this method returns instance of the model, not HttpResponseMessage.

Note: I am using MVC 4, Visual Studio 2010, EntityFramework 4.3

What should I change in the method above?

P.S. Would it be better if I just return empty instance created with

myTable = db.MyTableDbSet.Create(); 
like image 258
Vlad Avatar asked Nov 25 '25 20:11

Vlad


1 Answers

I find myself comfortable with this kind of approach:

[HttpGet]
public IHttpActionResult GetMyTable(byte id, string langid)
{
    var mytable = db.MyTables.Find(id, langid);

    if (mytable  != null)
    {
        return Ok(mytable);
    }
           
    return NotFound();
}
like image 196
Giovanni Romio Avatar answered Nov 28 '25 17:11

Giovanni Romio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!