Как отобразить пользовательские ошибки Результат JSON в WEB.API - PullRequest
0 голосов
/ 04 июня 2018

Я новичок в Web.API.У меня есть URL

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

Если предположить, по ошибке я использовал location вместо locationID в приведенном выше URL, он показывает Ошибка .Вместо этого мне нужно вернуть следующий результат JSON.

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

Как можно показать, что результат JSON вместо этой предопределенной ошибки в Web.API?

1 Ответ

0 голосов
/ 04 июня 2018

Попробуйте использовать обработчик Application_Error в 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();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...