csharp 通过HTTP状态代码处理全局应用程序异常

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 通过HTTP状态代码处理全局应用程序异常相关的知识,希望对你有一定的参考价值。

(function () {
    "use strict";
    
    // To regiester the interceptor, add the following line to your app.js -> .config():
    //     $httpProvider.interceptors.push("httpRequestInterceptorFactory");

    angular
        .module("MyApp.Common")
        .factory("httpRequestInterceptorFactory", HttpRequestInterceptorFactory);

    HttpRequestInterceptorFactory.$inject = ["$rootScope", "$q", "NotificationService"];
    function HttpRequestInterceptorFactory($rootScope, $q, NotificationService) {
        return {
            responseError: function (rejection) {
                // For expected errors such as failed model validation
                //simply return a promise and handle it further

                // used for when user is not authorized to access a WebAPI controller method
                if (rejection.status === 401) {
                    $rootScope.$broadcast("unauthorized-request");
                }
                // used for when the WebAPI endpoint does not exist
                else if (rejection.status === 404) {
                    $rootScope.$broadcast("error-message", { message: "Page does not exist", status: 404 });
                }
                // used for "item with same XY (for example "name") already exists"
                else if (rejection.status === 409) {
                    NotificationService.showWarning(rejection.data);
                }
                // used for invalid .net ModelState
                else if (rejection.status === 422) {
                    // invalid model states handled in controllers
                }

                //console.log(rejection);
                //console.log(rejection.data);

                if (rejection.data && rejection.data.exceptionMessage)
                    NotificationService.showWarning(rejection.data.exceptionMessage);

                return $q.reject(rejection);
            }
        };
    }
})();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using System.Web.Http.ExceptionHandling;
using MyApp.Web.Infrastructure.Filters;

namespace MyApp.Web
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Filters.Add(new ApplicationExceptionHandler());

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.Filters;

namespace MyApp.Web.Infrastructure.Filters
{
    /// <summary>
    /// Used to globally handle unhandled exceptions types.
    /// </summary>
    public class ApplicationExceptionHandler : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            // used for when user is not authorized to access a WebAPI controller method
            if (context.Exception is UnauthorizedAccessException)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }
            // used for "item with same XY (for example "name") already exists"
            else if (context.Exception is ArgumentException)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Conflict)
                {
                    Content = new StringContent(context.Exception.Message)
                };

                throw new HttpResponseException(response);
            }
            // used for exceptions that do not make sense from the business logic point of view
            else if (context.Exception is InvalidOperationException)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Conflict)
                {
                    Content = new StringContent(context.Exception.Message)
                };

                throw new HttpResponseException(response);
            }
        }
    }
}

以上是关于csharp 通过HTTP状态代码处理全局应用程序异常的主要内容,如果未能解决你的问题,请参考以下文章

csharp 状态代码重定向的异常处理

微信小程序实现全局搜索代码高亮

golang http 恐慌的全局恢复处理程序

SpringBoot全局异常处理与定制404页面

SpringBoot全局异常处理与定制404页面

csharp 用于处理.net模型状态的可重用ValidationFilter属性