[英]Handling 404 Not Found for WebApi
我正在創建一個
Asp.Net MVC + AngularJS
應用。 在WebApi控制器中,我已經處理了各種異常(500、404等)。 另一方面,所有未處理的異常都被捕獲
的Global.asax.cs
文件的
應用程序錯誤
方法。 但是,如果應用程序缺少整個API,則會按預期在瀏覽器的控制台上顯示404錯誤,但是在這種情況下,我也需要重定向到適當的UI(html / cshtml)。 如何處理此類異常?
PS我嘗試使用
的customErrors
物業
Web.config文件
文件,但它是徒勞的。
您需要執行以下步驟,
請關注Imran Baloch撰寫的本教程,以獲取詳細信息
以下是一些有關如何處理API錯誤以執行重定向的方法。
$(document)
.ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.status == 404) {
window.location.replace("http://www.stackoverflow.com");
}
});
$.ajaxSetup({
global: true,
error: function(xhr, status, err) {
if (xhr.status == 404) {
window.location.replace("http://www.stackoverflow.com");
}
}
});
如果您想要有角度的方法,則可以將[Javascript] Global Ajax錯誤處理程序與AngularJS結合使用 。
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'response': function(response) {
// do something on success
return response || $q.when(response);
},
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise;
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
angular.module("globalErrors", ['appStateModule']).factory "myHttpInterceptor", ($q, $log, growl) ->
response: (response) ->
$log.debug "success with status #{response.status}"
response || $q.when response
responseError: (rejection) ->
$log.debug "error with status #{rejection.status} and data: #{rejection.data['message']}"
switch rejection.status
when 404
window.location.replace("http://www.stackoverflow.com");
else
console.log(rejection.status);
# do something on error
$q.reject rejection
.config ($provide, $httpProvider) ->
$httpProvider.interceptors.push('myHttpInterceptor')
這基於AngularJS 1.1.4。 如果您使用的是其他版本,則可以應用類似的策略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.