正如您所說的,返回類型是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);
}
正是我一直在尋找for.thank你! –