处理FSX脚本中F#类型提供程序引发的异常

处理FSX脚本中F#类型提供程序引发的异常,f#,type-providers,F#,Type Providers,我有一个FSX脚本,其中包括一个类型提供程序。当脚本运行时,我希望在类型提供程序抛出异常时显示一条用户友好的消息。(例如,当SqlDataProvider无法连接到数据库时。) 可能吗 这显然行不通,但说明了这一想法: type Sql = try SqlDataProvider< DatabaseVendor = databaseVendor, ConnectionString = connectionString, TableNames = tableNames

我有一个FSX脚本,其中包括一个类型提供程序。当脚本运行时,我希望在类型提供程序抛出异常时显示一条用户友好的消息。(例如,当
SqlDataProvider
无法连接到数据库时。)

可能吗

这显然行不通,但说明了这一想法:

type Sql =
    try
        SqlDataProvider< DatabaseVendor = databaseVendor, ConnectionString = connectionString, TableNames = tableNames >
    with ex ->
        printfn "Cannot connect to the database."
类型Sql=
尝试
SqlDataProvider
使用ex->
printfn“无法连接到数据库。”

是可用于测试潜在解决方案的要点。

当脚本运行时,将引发异常,但除非您使用或实例化类型提供程序中的类型

在您的情况下,您不会在try中包装类型的定义,而是包装用法:

type Sql = SqlDataProvider<...>

// When you go to _use_ the type, handle exceptions:
try
    let ctx = Sql.GetDataContext ()
    // .. use
with
| :? SomeExceptionType as ex -> printfn "Cannot connect to the database."
type Sql=SqlDataProvider
//当您转到“使用”类型时,处理异常:
尝试
设ctx=Sql.GetDataContext()
// .. 使用
具有
| :? SomeExceptionType as ex->printfn“无法连接到数据库。”

当我使用“Microsoft(R)F#Interactive version 10.6.0.0 for F#4.7”运行本要点中的代码时,不会运行异常处理@Wallackelly你真的在使用上下文吗?我认为当上下文访问实际发生时,异常会在运行时抛出。我最初并没有使用它。然而,我只是更新了要点并重新测试。在这两种情况下,脚本都会失败,并出现编译器错误FS3033,因此不会让异常处理有机会运行。