2017-05-30 21 views
0

我正在使用Azure移动应用程序表控制器。获得语法Azure移动应用程序表控制器中的异常处理

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

现在,这里的问题是,由于回报率的方法是IQueryable的,我不能够捕捉异常的catch块,我明白了IQueryable的是从客户的不同要求(在我的情况下,机器人) 。但是我想在catch块中记录错误。目前我的调试器从未登陆catch块。因为Azure移动应用sdk处理异常并形成http异常,我可以看到的只有500异常。我想记录数据库中的错误,我如何实现这一目标?

回答

1

正如您所说的,返回类型是IQueryable,所以您无法捕获GetAllEmployee方法中的异常。

这是一个解决方法。

我建议你可以使用web api global error handling来处理异常。更多细节,你可以参考这个article及以下代码。

在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); 
     } 
+0

正是我一直在寻找for.thank你! –

相关问题