简体   繁体   English

如何在WEB.API中显示自定义错误JSON结果

[英]How to Display custom errors JSON Result in WEB.API

I'M new to Web.API . 我是Web.API I've the URL 我有网址

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

If suppose, by mistake i used location instead of locationID in the above URL it showing Error . 如果可以的话,我在上面的URL中错误地使用了location而不是locationID ,它显示了Error Instead of that i need to return the following JSON Result. 相反,我需要返回以下JSON结果。

 { "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? 如何显示JSON结果而不是Web.API中的预定义错误?

Try using Application_Error handler in Global.asax: https://msdn.microsoft.com/en-us/library/24395wz3.aspx 尝试在Global.asax中使用Application_Error处理程序: https : //msdn.microsoft.com/zh-cn/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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM