javascript - 如何在 WEB.API 中显示自定义错误 JSON 结果
问题描述
我是新手Web.API
。我有网址
http://localhost:21923/communities/getPost/locationID=1。
如果假设,我错误地使用location
而不是locationID
在上面的 URL 中显示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 - 从 Facebook 帖子打开 Chrome/Firefox (Android OS) 的 URL 方案
- javascript - 输入文本(数字),复选框值(文本)输出结果
- c# - C#网络浏览器历史
- ethereum - 限制发件人提取超过可用余额
- c++ - Byte order of fields when parsing network header
- c - 有没有办法 malloc 数组大小为 10 的整数指针并返回其值?
- vim - 当我在 vim 中输入 '-' 字符时,它似乎正在打印回车,然后是 'm'
- python-3.x - 如何使python脚本实时更新(连续运行)
- c++ - 如何在 c++ 中排序最大值?
- python - Python-得到一个快速排序递归错误