Azure 移动应用 table 控制器中的异常处理

Exception handling in Azure mobile app table controller

我正在使用 Azure 移动应用 table 控制器。获取语​​法是

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

现在的问题是,由于 return 方法是 IQueryable,我无法在 catch 块中捕获异常,我知道 IQueryable 是针对来自客户端的不同请求(在我的例子中 android).但是我想在 catch block.currently 中记录错误,我的调试器从未进入 catch 块。因为 azure 移动应用程序 sdk 处理异常并形成 http 异常,我只能看到 500 异常。我想在数据库中记录错误,我该如何实现?

正如您所说,return 类型是 IQueryable,因此您无法在 GetAllEmployee 方法中捕获异常。

这里有一个解决方法。

我建议您可以使用网页 api global error handling to handle the exception. More details, you could refer to this article 及以下代码。

在Startup.MobileApp.cs:

添加这个 class:

  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);
        }