0

I am trying to implement error handling in my WebAPI and I have ErrorController.cs with the following code:

public class ErrorController : ApiController
{
    [HttpGet, HttpPost, HttpPut, HttpDelete, HttpHead, HttpOptions, AcceptVerbs("PATCH")]
    public HttpResponseMessage Handle404()
    {
        var responseMessage = new HttpResponseMessage(HttpStatusCode.NotFound);
        responseMessage.ReasonPhrase = "The requested resource is not found";
        return Request.CreateResponse(new { error = "The requested resource is not found" });
    }
}

I make an API call like this:

http://localhost:46151/api/TData?ROOM=ABC&DOB_GT=01-SEP-05&DOB_LT=30-DEC-06&STATUS_TYPE=CMT

In order to force an error to occur I tried mispelling one of the query parameters (from DOB_LT to DO_LT) to check how errors are being handled -- like this:

http://localhost:46151/api/TData?ROOM=ABC&DOB_GT=01-SEP-05&DO_LT=30-DEC-06&STATUS_TYPE=CMT

The debugger breaks in ErrorController as shown in the image below:

enter image description here

Tried try Catch block like

        catch (Exception ex)
         {
             var returnObj = new { error = ex.Message };
             var response = Request.CreateResponse(HttpStatusCode.BadRequest, returnObj, MediaTypeHeaderValue.Parse("application/json"));
             ContentDispositionHeaderValue contentDisposition = null;
             if (ContentDispositionHeaderValue.TryParse("inline; filename=error.json", out contentDisposition))
             {
                 response.Content.Headers.ContentDisposition = contentDisposition;
             }
             return response;
         }
trx
  • 2,077
  • 9
  • 48
  • 97
  • Take a good look at the following post: http://stackoverflow.com/questions/20139621/how-do-i-return-notfound-ihttpactionresult-with-an-error-message-or-exception -- especially the one-line solution presented by @AnthonyF – David Tansey Nov 22 '16 at 04:23
  • @DavidTansey Do I use `return Content(HttpStatusCode.NotFound, "Foo does not exist.");` in my catch block? – trx Nov 22 '16 at 04:28
  • I just the found the sample that you are probably working from -- I hope I have not mislead you. More info when I get a closer look at the sample. – David Tansey Nov 22 '16 at 04:36
  • Yes from another controller. What I am trying to do is the current API returns query result in JSON. Likewise I want to return the error messages or exception as JSON like `{"error":" Exception Message"}. I tried using the try catch block in the controller as I edited in my question but this is not working – trx Nov 22 '16 at 04:36
  • @DavidTansey Yes please help out with this. I will have to return the exception in JSON – trx Nov 22 '16 at 04:48
  • @trx Why don't you use exception filter for that? – kamil-mrzyglod Nov 22 '16 at 08:29

0 Answers0