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

Viewed 1300

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(); 
2 Answers
Related