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

标签 javascript json asp.net-web-api exception

我是 Web.API 的新手。我有网址

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

如果假设,我错误地在上面的 URL 中使用了 location 而不是 locationID,它显示 Error 。相反,我需要返回以下 JSON 结果。

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

如何显示 JSON 结果而不是 Web.API 中的预定义错误?

最佳答案

尝试在 Global.asax 中使用 Application_Error 处理程序: 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();
}

关于javascript - 如何在 WEB.API 中显示自定义错误 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50673873/

相关文章:

Android改造转换器异常

facebook - 在 Web API 中返回 401 Facebook 登录

c# - ApiController 中的 Request.AnonymousID

Javascript 垂直、水平缩放图像和变换图像位置

javascript - PrototypeJS:是否可以删除或撤消其全局修改?

javascript - 延迟在 jquery 动画队列中没有正确重新初始化

rest - ASP.NET Web Api 重复动词

javascript - 单击导航栏时将类设置为在其他 li 元素上处于事件状态

javascript - 大小与 ArcGIS Javascript SimpleMarkerSymbol JSON 构造函数不一致

java - 找不到 org.jose4j.json.internal.json_simple