c# - 如何使用 MVC 自定义页面错误管理处理 angularjs HTTP 错误?
问题描述
• 我需要通过重定向到我自己的自定义错误页面来管理未找到的页面和服务器问题错误,所以我通过以下方式完成了这项工作,并且工作正常。
网络配置
<customErrors mode="On">
<error statusCode="400" redirect="~/Error/Error400"/>
<error statusCode="404" redirect="~/Errors/Error404" />
<error statusCode="403" redirect="~/Error/Error403" />
<error statusCode="500" redirect="~/Errors/Error500" />
</customErrors>
• 现在,当我需要angularjs http
通过以下代码获取类似 404 的错误时,其中传递了控制器中不可用的错误方法 (GetDetai)(实际上是“GetDetails”)。
$http({
method: 'GET',
url: '/Admin/Dashboard/GetDetai',
headers: { "Content-Type": "application/json" }
}).then(function (result) {
console.log(result);
$scope.GetCustomer = result.data;
}, function (reason) {
console.log(reason);
if (reason.status == '404') {
console.log('Invalid Method/URL.');
}
else if (reason.status == '505') {
console.log('Internal server error.');
}
});
• then 它没有在错误函数中捕获 404 错误,它进入 then 函数并显示在下面
第一个控制台日志输出
{data: "
↵
↵
↵<!DOCTYPE html>
↵<html>
↵<head>
↵ <meta c…white;">Go Back To Home</a>
↵</body>
↵</html>
↵
↵", status: 200, config: {…}, statusText: "OK", headers: ƒ, …}
data: "
↵
↵
↵<!DOCTYPE html>
↵<html>
↵<head>
↵ <meta charset="utf-8" />
↵ <title></title>
↵ <style>
↵ body {
↵ display: inline-block;
↵ background: #00AFF9 url(https://cbwconline.com/IMG/Codepen/Unplugged.png) center/cover no-repeat;
↵ height: 100vh;
↵ margin: 0;
↵ color: white;
↵ }
↵
↵ h1 {
↵ margin: .8em 3rem;
↵ font: 4em Roboto;
↵ }
↵
↵ p {
↵ display: inline-block;
↵ margin: .2em 3rem;
↵ font: 2em Roboto;
↵ }
↵ </style>
↵</head>
↵<body>
↵ <h1>Whoops!</h1>
↵ <p>Something went wrong</p><br /><br />
↵
↵ <a href="/Home/Index" style="color:white;">Go Back To Home</a>
↵</body>
↵</html>
↵
↵"
status: 200
headers: ƒ (name)
config: {method: "GET", transformRequest: Array(1), transformResponse: Array(1), jsonpCallbackParam: "callback", paramSerializer: ƒ, …}
statusText: "OK"
xhrStatus: "complete"
__proto__: Object
• 但是,当我评论/删除 web.config 自定义错误代码时,此angularjs http
调用错误函数正常工作,得到预期的 404 错误。
那么如何在不依赖和不影响其他代码的情况下正确管理这两种错误呢?
解决方案
您的 HTTP 调用返回状态“200”,即“OK”,因此您看不到 HTTP ERRORS 处理检索数据时引发的错误:
$http({
...
})
.then(
function (result) {
console.log(result);
//Line below is not invoked as result.data != "Exception"
if (result.data == "Exception") {
...
}
else {
...
//This assignes result.data to GetCustomer in scope
//and at late stage of processing retrieved data rose exception...
$scope.GetCustomer = result.data;
}
},
function (reason) { //This code is not invoking as http.resultCode="200" ("OK")
...
}
);
推荐阅读
- php - 权限被拒绝麻烦 Laravel,在 centos 7
- python - 如何删除具有所有零值但不具有非零值的零的行
- xamarin - 任务被取消 Xamarin 异常
- html - $@Html.DisplayFor( 在桌子上给了我一个数字,我想使用那个数字,以便 IF 给我那个值
- python - 将输入分解为列出的频率
- arrays - 我可以创建在算法之前没有大小的整数数组吗?
- python - Python selenium - 使用嵌入式 webdriver 和浏览器编译
- javascript - 在javascript中找到给定位的值
- javascript - Flask - 将大型 JSON 对象传递给模板的最佳方法
- javascript - 嵌套 for 循环以从嵌套数组创建节/div