首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Lwt和Cohttp:“exception :exception Unix.Unix_error(Unix.ECONNRESET,"read",”“)

Lwt和Cohttp:“exception :exception Unix.Unix_error(Unix.ECONNRESET,"read",”“)
EN

Stack Overflow用户
提问于 2016-11-08 22:14:56
回答 1查看 637关注 0票数 1

我在Ocaml中有一个简单的HTTP服务器,带有Cohttp和Lwt。当我运行wrk时,一旦wrk完成,应用程序就会崩溃约50%。我认为崩溃是由意外的断开连接触发的。

我在控制台上看到了以下错误:

代码语言:javascript
复制
Fatal error: exception Unix.Unix_error(Unix.ECONNRESET, "read", "")
Raised by primitive operation at file "src/unix/lwt_bytes.ml", line 130, characters 42-84
Called from file "src/unix/lwt_unix.ml", line 489, characters 13-24

有办法阻止这件事吗?

我的完整源代码是:

代码语言:javascript
复制
(* server_test.ml *)
open Unix
open Lwt
open Cohttp
open Cohttp_lwt_unix
open Yojson
open Yojson.Basic.Util
open Core.Std

type create = {
username: string;
email: string;
password: string;
} [@@deriving yojson]

let insert coll doc =
    let _id = Core.Std.Uuid.to_string (Uuid.create ()) in
    let uri = Uri.make ~scheme:"http" ~host:"127.0.0.1" ~port:5984 ~path:(coll ^ "/" ^ _id) () in
    Cohttp_lwt_unix.Client.put ~body:(Cohttp_lwt_body.of_string (Yojson.Safe.to_string doc)) uri
    >|= fun (r, _) -> Code.code_of_status @@ Response.status r

let callback _conn req body =
    body |> Cohttp_lwt_body.to_string 
    >>= (fun body -> 
        let mc = Yojson.Safe.from_string body |> create_of_yojson in
        match mc with
        | Ok c -> 
            insert "users" (create_to_yojson c)
            >>= fun status -> print_endline @@ string_of_int status; 
                Server.respond_string ~status:(`Code status) ~body:(string_of_int status) ()
        | _ -> Server.respond_string ~status:`OK ~body: "Not OK" ())

let timeit _conn req body =
    let start = Unix.gettimeofday () in
    callback _conn req body 
    >>= 
    fun result ->
        let finish = Unix.gettimeofday () in
        Lwt_io.printlf "Execution time took %fms" ((finish -. start) *. 1000.0)
        >|= fun _ -> result

let server =
    Server.create ~mode:(`TCP (`Port 8000)) (Server.make timeit ())

let () = ignore (Lwt_main.run server)

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-08 22:24:48

您所看到的错误来自于客户端意外断开连接时引发的未处理异常。相关的异常被传递给Lwt的异步异常钩子(hook),在Lwt的默认情况下,它打印一个回溯并使用2的退出代码退出程序。

在cohttp github问题跟踪器:https://github.com/mirage/ocaml-cohttp/issues/511上正在对此进行讨论。

简而言之,如果您为Lwt的异步/“后台”线程定义了一个自定义异常处理程序,那么您可以捕获和忽略/log/处理客户端错误。在启动cohttp服务器之前添加如下内容:

代码语言:javascript
复制
Lwt.async_exception_hook := (function
  | Unix.Unix_error (error, func, arg) ->
    Logs.warn (fun m ->
      m  "Client connection error %s: %s(%S)"
        (Unix.error_message error) func arg
    )
  | exn -> Logs.err (fun m -> m "Unhandled exception: %a" Fmt.exn exn)
);

https://github.com/mirage/ocaml-cohttp/issues/511#issuecomment-258510531获取并使用logs库记录事件:http://erratique.ch/software/logs

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40497364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档