Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #26 from flatiron/connect-compatible-error-handling

[api] Implement next(err) and modify errorHandling
  • Loading branch information...
commit dda33b166ba421cd1bbcbb65f6e1d09e12e027dc 2 parents 1715e55 + 81fbc95
@pksunkara pksunkara authored
Showing with 42 additions and 10 deletions.
  1. +23 −0 README.md
  2. +12 −7 lib/core.js
  3. +7 −3 lib/routing-stream.js
View
23 README.md
@@ -143,6 +143,29 @@ An example of the `headers` option.
}
```
+## Error Handling
+Error handler is similiar to middlware but takes an extra argument for error at the beginning.
+
+```js
+var handle = function (err, req, res) {
+ res.statusCode = err.status;
+ res.end(req.headers);
+};
+
+var server = union.createServer({
+ onError: handle,
+ before: [
+ favicon('./favicon.png'),
+ function (req, res) {
+ var found = router.dispatch(req, res);
+ if (!found) {
+ res.emit('next');
+ }
+ }
+ ]
+});
+```
+
## BufferedStream Constructor
This constructor inherits from `Stream` and can buffer data up to `limit` bytes. It also implements `pause` and `resume` methods.
View
19 lib/core.js
@@ -36,7 +36,12 @@ core.createServer = function (options) {
headers: options.headers
});
- routingStream.on('error', options.onError || core.errorHandler.bind({ res: res }));
+ routingStream.on('error', function (err) {
+ var fn = options.onError || core.errorHandler;
+ fn(err, routingStream, routingStream.target, function () {
+ routingStream.target.emit('next');
+ });
+ });
req.pipe(routingStream);
}
@@ -60,13 +65,13 @@ core.createServer = function (options) {
return http.createServer(requestHandler);
};
-core.errorHandler = function error(err) {
+core.errorHandler = function error(err, req, res) {
if (err) {
- this.res.writeHead(err.status || 500, err.headers || { "Content-Type": "text/plain" });
- this.res.end(err.stack + "\n");
+ res.writeHead(err.status || 500, err.headers || { "Content-Type": "text/plain" });
+ res.end(err.stack + "\n");
return;
}
- this.res.writeHead(404, {"Content-Type": "text/plain"});
- this.res.end("Not Found\n");
-};
+ res.writeHead(404, {"Content-Type": "text/plain"});
+ res.end("Not Found\n");
+};
View
10 lib/routing-stream.js
@@ -108,8 +108,12 @@ RoutingStream.prototype.route = function (req) {
self.target.once('next', dispatch.bind(null, i));
if (self.before[i].length === 3) {
- self.before[i](self, self.target, function () {
- self.target.emit('next');
+ self.before[i](self, self.target, function (err) {
+ if (err) {
+ self.onError(err);
+ } else {
+ self.target.emit('next');
+ }
});
}
else {
@@ -120,4 +124,4 @@ RoutingStream.prototype.route = function (req) {
RoutingStream.prototype.onError = function (err) {
this.emit('error', err);
-};
+};
Please sign in to comment.
Something went wrong with that request. Please try again.