【问题标题】:Postgresql-Ocaml Bindings and ErrorsPostgresql-Ocaml 绑定和错误
【发布时间】:2013-12-27 04:54:44
【问题描述】:

以下代码在数据库已创建时有效,但如果未创建数据库则失败。对我来说更令人担忧的问题是,我的代码没有捕捉到未创建数据库时代码引发的错误。我是 Ocaml 错误处理的新手,所以我想知道为什么这不起作用。这是我收到的错误:

Fatal error: exception Postgresql.Error(_)

这是我的代码:

open Postgresql;;

let main () = ( 
  let c = new connection ~host:"localhost" ~port:"5432" ~dbname:"stocks" ~user:"postgres"
    ~password:"postgres" ()  in  
  let status ()  = (   
  try match c#status with 
    | Ok -> print_string ("STATUS CONNECTED\n"); 
    | Bad -> print_string "BAD";
  with Error(s) ->( print_string (string_of_error(s))))  in  
  status();  

  c#finish   
);;

main();; 

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    很可能在let c = .... 语句中引发异常,因为它不在try....with 块内。下面的代码示例并不理想,但比您拥有的更多 OCaml 方式。

     open Postgresql
    
     let with_connection f =
       try
         let c = new connection ~host:"localhost" ~port:"5432" ~dbname:"stocks" ~user:"postgres"
           ~password:"postgres" () in
         f c;
         c#finish
       with _ -> print_endline "ERROR"
    
     let main () = 
       with_connection (fun c ->  
         try match c#status with 
           | Ok -> print_string ("STATUS CONNECTED\n"); 
           | Bad -> print_string "BAD";
         with Error(s) ->( print_string (string_of_error(s))))  
        )
    
    
     let () = main ()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 2012-11-21
      • 1970-01-01
      • 2013-09-19
      • 2020-04-18
      • 1970-01-01
      相关资源
      最近更新 更多