Javascript 如何在WEB.API中显示自定义错误JSON结果
我不熟悉Javascript 如何在WEB.API中显示自定义错误JSON结果,javascript,json,asp.net-web-api,exception-handling,Javascript,Json,Asp.net Web Api,Exception Handling,我不熟悉Web.API。我有网址 如果假设,我在上面显示的URL中错误地使用了location而不是locationID。相反,我需要返回以下JSON结果 { “消息”:“参数不匹配”, “错误代码”:404(或)其他东西, “状态”:错误 }尝试在Global.asax中使用应用程序错误处理程序: void应用程序\u错误(对象发送方,事件参数e) { //发生未处理错误时运行的代码 //获取异常对象。 异常exc=Server.GetLastError(); //通过发送JSON处理H
Web.API
。我有网址
如果假设,我在上面显示的URL中错误地使用了location
而不是locationID
。相反,我需要返回以下JSON结果
{
“消息”:“参数不匹配”,
“错误代码”:404(或)其他东西,
“状态”:错误
}
尝试在Global.asax中使用应用程序错误处理程序:
void应用程序\u错误(对象发送方,事件参数e)
{
//发生未处理错误时运行的代码
//获取异常对象。
异常exc=Server.GetLastError();
//通过发送JSON处理HTTP错误(仅适用于HTTP错误)
if(exc.GetType()==typeof(HttpException))
{
//完整的错误处理示例生成
//使用带有“NoCatch”的URL时出现一些错误;
//忽略这些,以模拟将发生的情况
//如果未实现global.asax处理程序。
if(exc.Message.Contains(“NoCatch”)| | exc.Message.Contains(“maxurlength”))
返回;
//返回一个JSON对象
Write(JsonConvert.SerializeObject)(新
{
“消息”:“参数不匹配”,
“错误代码”:“404(或)其他内容”,
“状态”:错误
})
);
}
//对于其他类型的错误,请向用户提供一些信息
//但请保持在默认页面
Write(“全局页面错误\n”);
回答,写(
“”+exc.Message+”\n”);
Response.Write(“返回到\n”);
//记录异常并通知系统操作员
日志异常(exc,“DefaultPage”);
例外功能。通知系统操作(exc);
//清除服务器上的错误
ClearError();
}
你应该看看我已经看过了。但是,编译器需要执行该方法,然后它将检查该ID是否存在。如果不是,那么它就是一个错误。但是,在我的情况下,它甚至不会进入行动方法。谢谢它的工作。但是,如何在errorCode中获取404或500等错误代码?将exc转换为HttpExeception,并使用GetHttpCode()方法获取状态代码的int值:“errorCode”:((HttpException)exec).GetHttpCode()代码>
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();
}