簡體   English   中英

Azure移動應用程序表控制器中的異常處理

[英]Exception handling in Azure mobile app table controller

我正在使用Azure移動應用程序表控制器。 得到的語法是

    public IQueryable<Employee> GetAllEmployee()
    {
        try
        {
        return Query();
        }
        catch(Exception ex)
        {
            throw;
        }
    }

現在的問題是,由於return方法是IQueryable,因此我無法在catch塊中捕獲異常,我知道IQueryable是針對來自客戶端(在我的情況下為android)的不同請求的。 但是我想在catch塊中記錄錯誤。當前,我的調試器從不進入catch塊。 因為azure移動應用程序sdk處理異常並形成http異常,我只能看到500個異常。 我想在數據庫中記錄錯誤,我該如何實現?

正如您所說的,返回類型是IQueryable,因此您無法在GetAllEmployee方法中捕獲異常。

這是一個解決方法。

我建議您可以使用Web API 全局錯誤處理來處理異常。 更多詳細信息,您可以參考本文和下面的代碼。

在Startup.MobileApp.cs中:

添加此類:

  public class TraceSourceExceptionLogger : ExceptionLogger
    {
        private readonly TraceSource _traceSource;

        public TraceSourceExceptionLogger(TraceSource traceSource)
        {
            _traceSource = traceSource;
        }

        public override void Log(ExceptionLoggerContext context)
        {
            //in this method get the exception details and add it to the sql databse
            _traceSource.TraceEvent(TraceEventType.Error, 1,
                "Unhandled exception processing {0} for {1}: {2}",
                context.Request.Method,
                context.Request.RequestUri,
                context.Exception);
        }
    }

更改ConfigureMobileApp方法,如下所示:

  public static void ConfigureMobileApp(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            config.Services.Add(typeof(IExceptionLogger),
    new TraceSourceExceptionLogger(new
    TraceSource("MyTraceSource", SourceLevels.All)));


            new MobileAppConfiguration()
                .UseDefaultConfiguration()
                .ApplyTo(config);

            // Use Entity Framework Code First to create database tables based on your DbContext
            Database.SetInitializer(new MobileServiceInitializer());

            MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();

            if (string.IsNullOrEmpty(settings.HostName))
            {
                app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
                {
                    // This middleware is intended to be used locally for debugging. By default, HostName will
                    // only have a value when running in an App Service application.
                    SigningKey = ConfigurationManager.AppSettings["SigningKey"],
                    ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
                    ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
                    TokenHandler = config.GetAppServiceTokenHandler()
                });
            }

            app.UseWebApi(config);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM