luvit/luvit — pull request #433 by Kami (2013-11-27 19:47:37+00:00)
Title: Emit "parse" error onthe request instead of the response object.

## Problem Description

Currently `parse error` is emitted on `Response` object. This doesn't work well if you use `http.request` method.

The problem is that `error` is emitted before `http.request` callback is called. This means you don't have a chance to add `error` handler to the response object which causes an unhandled error.

Code which reproduces it:

```lua
local http = require('http')

local req = http.request({
host = 'luvit.io',
port = 22,
path = '/'
}, function (res)
res:on('error', function(err)
msg = tostring(err)
print('Error while receiving a response: ' .. msg)
end)

res:on('data', function (chunk)
p('ondata', {chunk=chunk})
end)
res:on('end', function ()
res:destroy()
end)
end)

req:on('error', function(err)
msg = tostring(err)
print('Error while sending a request: ' .. msg)
end)

req:done()
```

Error
```bash
luvit test.lua
"UNHANDLED ERROR"	"parse error"
/w/luvit/lib/luvit/core.lua:162: UNHANDLED ERROR. Define process:on('error', handler) to catch such errors
```

As you can see, I did add listener for the `error` event, but this doesn't make a difference since `error` is emitted before the callback is called (https://github.com/luvit/luvit/blob/master/lib/luvit/http.lua#L787, https://github.com/luvit/luvit/blob/master/lib/luvit/http.lua#L623).

## Proposed Solution

I've updated the code to emit this error on request instead of response object. This seems like a reasonable solution to me and works fine because you have access to the request object as soon as you call `http.request` which means you can add `error` handler early enough.