Unable to call dispose on domain at appropriate time

狂风中的少年 提交于 2020-01-03 18:57:33

问题


I'm having an issue with the domain module. Currently, I'm trying to catch any uncaught errors that are thrown in a request. Using an express middleware and domains. All requests are routed through this function before calling next and moving on to it's proper route.

app.use (req, res, next) ->
    domain = createDomain()
    domain.on "error", (err) ->
        res.send(500)
        domain.dispose()

    domain.enter()
    next()

The problem is, how do I dispose of the domain if an error is never thrown?

I could hoist the domain and event outside the middlewear so I don't ever have to dispose, but then I won't have access to middlewear args that I need to send a 500.

Does anyone have a better solution to how I am handling this? I've spent way too much time trying to figure out a way (and many hacky ways) to handle this. Thanks.


回答1:


You do not need to call domain.dispose() if no errors occurred. The purpose of domain.dispose() is to clean up any resources that were left in an indeterminate state after jumping out out the middle of the stack, and to squelch subsequent errors that would occur due to the bad state. The inverse call of domain.enter() is simply domain.exit().

That said, browsing through the code for domains, it looks like you don't want to use domain.enter/exit this way. Each domain.enter/exit corresponds to a stack push/pop of a shared array in the domain module code. So, for example, if a second request comes in before the first one has completed, and then the first one exits before the second one does, calling exit in the first domains handler will pop the domain for the second request. It seems quite likely that enter and exit should not be split across asynchronous things.

Have you tried simply using domain.run(next)? That seems to do the trick for me. It basically enters the domain for you and then calls the callback you give to it, and then immediately exits the domain after the callback returns. Any timers or event emitters created while you are in the domain will associate themselves with that domain, as well. Event emitters then also use a similar enter-call-exit pattern when calling event handlers. It appears in the code that it is not domains that track event handlers, but rather event handlers that track domains.

In short, don't try to pair an enter with a dispose, and don't try to use enter/exit across asynchronous boundaries. Use run/bind/add/remove.



来源:https://stackoverflow.com/questions/14971028/unable-to-call-dispose-on-domain-at-appropriate-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!