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:
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;
}