0

I'M new to Web.API. I've the URL

http://localhost:21923/communities/getPost/locationID=1.

If suppose, by mistake i used location instead of locationID in the above URL it showing Error. Instead of that i need to return the following JSON Result.

{
  "message": "Parameter missmatch",
  "errorCode": 404 (or) something else,
  "Status": false
}

How can is show that JSON result instead of that pre-defined error in Web.API?

2
  • You should have a look at learn.microsoft.com/en-us/aspnet/web-api/overview/… Commented Jun 4, 2018 at 5:30
  • I've gone through that. But, there compiler need to go into action method then it'll check whether that ID is present or not. If not then it throwing error. But, in my case it won't even go in to action method. Commented Jun 4, 2018 at 5:34

1 Answer 1

1

Try using Application_Error handler in Global.asax: https://msdn.microsoft.com/en-us/library/24395wz3.aspx

void Application_Error(object sender, EventArgs e)
{
  // Code that runs when an unhandled error occurs

  // Get the exception object.
  Exception exc = Server.GetLastError();

  // Handle HTTP errors by sending the JSON (only for Http Error)
  if (exc.GetType() == typeof(HttpException))
  {
    // The Complete Error Handling Example generates
    // some errors using URLs with "NoCatch" in them;
    // ignore these here to simulate what would happen
    // if a global.asax handler were not implemented.
      if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
      return;

    //Return a JSON object
    Response.Write(JsonConvert.SerializeObject(new
    {
        "message": "Parameter missmatch",
        "errorCode": "404 (or) something else",
        "Status": false
    })
    );
  }

  // For other kinds of errors give the user some information
  // but stay on the default page
  Response.Write("<h2>Global Page Error</h2>\n");
  Response.Write(
      "<p>" + exc.Message + "</p>\n");
  Response.Write("Return to the <a href='Default.aspx'>" +
      "Default Page</a>\n");

  // Log the exception and notify system operators
  ExceptionUtility.LogException(exc, "DefaultPage");
  ExceptionUtility.NotifySystemOps(exc);

  // Clear the error from the server
  Server.ClearError();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it's working. But, how to get the error code like 404 or 500 or something else in errorCode?
Cast exc to HttpExeception and use GetHttpCode() method to get the int value of the status code: msdn.microsoft.com/en-us/library/… "errorCode": ((HttpException)exec).GetHttpCode();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.