Skip to content

Commit 3d363c4

Browse files
author
nicola
committed
fixing issues with errors and enabling custom error handlers
1 parent 8075e89 commit 3d363c4

11 files changed

Lines changed: 203 additions & 114 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,9 @@ In case the `settings` is not passed, then it will start with the following defa
7878
suffixAcl: '.acl', // Suffix for acl files
7979
suffixChanges: '.changes', // Suffix for acl files
8080
suffixSSE: '.events', // Suffix for SSE files
81-
proxy: false // Where to mount the proxy
81+
proxy: false, // Where to mount the proxy
82+
errorHandler: false, // function(err, req, res, next) to have a custom error handler
83+
errorPages: false // specify a path where the error pages are
8284
}
8385
```
8486

@@ -100,7 +102,7 @@ ldp.listen(3000, function() {
100102

101103
##### Advanced
102104

103-
You can integrate ldnode in your existing express app, by mounting the ldnode app on a specific path using `lnode(opts)`.
105+
You can integrate ldnode in your existing express app, by mounting the ldnode app on a specific path using `lnode(opts)`. Have a look at see [further examples](https://github.com/linkeddata/ldnode/tree/master/examples)
104106

105107
```javascript
106108
var ldnode = require('ldnode')

‎examples/custom-error-handling.js‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
var ldnode = require('../'); // or require('ldnode')
2+
var path = require('path');
3+
4+
ldnode
5+
.createServer({
6+
webid: true,
7+
cert: path.resolve('./test/keys/cert.pem'),
8+
key: path.resolve('./test/keys/key.pem'),
9+
errorHandler: function(err, req, res, next) {
10+
if (err.status !== 200) {
11+
console.log('Oh no! There is an error:' + err.message);
12+
res.status(err.status);
13+
14+
// Now you can send the error how you want
15+
// Maybe you want to render an error page
16+
// res.render('errorPage.ejs', {
17+
// title: err.status + ": This is an error!",
18+
// message: err.message
19+
// })
20+
// Or you want to respond in JSON?
21+
22+
res.json({
23+
title: err.status + ": This is an error!",
24+
message: err.message
25+
});
26+
}
27+
28+
}
29+
})
30+
.listen(3456, function() {
31+
console.log('started ldp with webid on port ' + 3456);
32+
});
33+

‎lib/acl.js‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ var debug = require('./logging').ACL;
1313
var utils = require('./utils.js');
1414
var ns = require('./vocab/ns.js').ns;
1515
var rdfVocab = require('./vocab/rdf.js');
16+
var HttpError = require('./http-error');
1617

1718
// TODO should this be set?
1819
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
@@ -44,12 +45,16 @@ ACL.prototype.readACL = function(pathAcl, pathUri, callback) {
4445
debug("Error parsing ACL policy: " + err.message);
4546
return callback(err);
4647
}
48+
4749
var aclGraph = $rdf.graph();
4850
try {
4951
$rdf.parse(aclData, aclGraph, pathUri, 'text/turtle');
50-
} catch (parseErr) {
51-
debug("Error parsing ACL policy: " + parseErr);
52-
return callback({ status: 500, message: parseErr });
52+
} catch (err) {
53+
debug("Error parsing ACL policy: " + err);
54+
return callback(new HttpError({
55+
status: 500,
56+
message: err.message
57+
}));
5358
}
5459

5560
return callback(null, aclGraph);
@@ -87,17 +92,17 @@ ACL.prototype.findACLinPath = function (mode, pathAcl, pathUri, aclGraph, access
8792
// User is authenticated
8893
if (userId.length === 0 || !acl.session || acl.session.identified === false) {
8994
debug("Authentication required");
90-
return callback({
95+
return callback(new HttpError({
9196
status: 401,
9297
message: "Access to " + pathUri + " requires authorization"
93-
});
98+
}));
9499
}
95100
// No ACL statement found, access is denied
96101
debug(mode + " access denied for: " + userId);
97-
return callback({
102+
return callback(new HttpError({
98103
status: 403,
99104
message: "Access denied for " + userId
100-
});
105+
}));
101106
});
102107
});
103108

‎lib/handlers/error.js‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ var fs = require('fs');
66
function errorPageHandler(err, req, res, next) {
77
var ldp = req.app.locals.ldp;
88

9+
// If the user specifies this function
10+
// then, they can customize the error programmatically
11+
if (ldp.errorHandler) {
12+
return ldp.errorHandler(err, req, res, next);
13+
}
14+
915
// If noErrorPages is set,
1016
// then use built-in express default error handler
1117
if (ldp.noErrorPages) {
@@ -18,7 +24,9 @@ function errorPageHandler(err, req, res, next) {
1824
var errorPage = ldp.errorPages + err.status.toString() + '.html';
1925
fs.readFile(errorPage, 'utf8', function(readErr, text) {
2026
if (readErr) {
21-
return next();
27+
return res
28+
.status(err.status)
29+
.send(err.message);
2230
}
2331

2432
res.status(err.status);

‎lib/handlers/get.js‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ var metadata = require('../metadata.js');
1616
var ns = require('../vocab/ns.js').ns;
1717
var utils = require('../utils.js');
1818
var subscription = require('../subscription.js');
19+
var HttpError = require('../http-error');
1920

2021
var ldpVocab = require('../vocab/ldp.js');
2122
var turtleExtension = '.ttl';
@@ -123,10 +124,10 @@ function globHandler(req, res, next) {
123124
glob(filename, globOptions, function(err, matches) {
124125
if (err || matches.length === 0) {
125126
debug("GET/HEAD -- No files matching the pattern");
126-
var globErr = new Error();
127-
globErr.status = 404;
128-
globErr.message = "No files matching glob pattern";
129-
return next(globErr);
127+
return next(new HttpError({
128+
message: "No files matching glob pattern",
129+
status: 404
130+
}));
130131
}
131132

132133
// Matches found
@@ -206,21 +207,22 @@ function parseLinkedData(req, res, next) {
206207
try {
207208
$rdf.parse(turtleData, resourceGraph, baseUri, 'text/turtle');
208209
} catch (err) {
209-
debug("GET/HEAD -- Error parsing data: " + err);
210-
var parseErr = new Error();
211-
parseErr.status = 500;
212-
parseErr.message = err.message;
213-
return next(parseErr);
210+
211+
debug("GET/HEAD -- Error parsing data: " + err.message);
212+
return next(new HttpError({
213+
message: err.message,
214+
status: 500
215+
}));
214216
}
215217

216218
// Graph to `accept` type
217219
$rdf.serialize(undefined, resourceGraph, null, accept, function(err, result) {
218220
if (result === undefined || err) {
219221
debug("GET/HEAD -- Serialization error: " + err);
220-
var serializeErr = {};
221-
serializeErr.status = 500;
222-
serializeErr.message = err.message;
223-
return next(serializeErr);
222+
return next(new HttpError({
223+
message: err.message,
224+
status: 500
225+
}));
224226
}
225227

226228
return res

‎lib/handlers/patch.js‎

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ var $rdf = require('rdflib');
88
var debug = require('../logging').handlers;
99
var utils = require('../utils.js');
1010
var subscription = require('../subscription.js');
11+
var HttpError = require('../http-error');
1112

1213
function handler(req, res, next) {
1314
var ldp = req.app.locals.ldp;
@@ -45,11 +46,10 @@ function handler(req, res, next) {
4546
res.send("Patch applied OK\n");
4647
});
4748
} else {
48-
var contentErr = new Error();
49-
contentErr.status = 400;
50-
contentErr.message = "Sorry unknowm patch content type: " +
51-
patchContentType;
52-
next(contentErr);
49+
return next(new HttpError({
50+
status: 400,
51+
message: "Sorry unknown patch content type: " + patchContentType
52+
}));
5353
}
5454
} // postOrPatch
5555

@@ -63,10 +63,10 @@ function sparql (filename, targetURI, text, callback) {
6363

6464
fs.readFile(filename, { encoding: 'utf8'}, function (err, dataIn) {
6565
if (err) {
66-
return callback({
66+
return callback(new HttpError({
6767
status: 404,
6868
message: "Patch: Original file read error:" + err
69-
});
69+
}));
7070
}
7171

7272
debug("PATCH -- File read OK "+dataIn.length);
@@ -75,10 +75,10 @@ function sparql (filename, targetURI, text, callback) {
7575
try {
7676
$rdf.parse(dataIn, targetKB, targetURI, targetContentType);
7777
} catch(e) {
78-
return callback({
78+
return callback(new HttpError({
7979
status: 500,
8080
message: "Patch: Target " + targetContentType + " file syntax error:" + e
81-
});
81+
}));
8282
}
8383
debug("PATCH -- Target parsed OK ");
8484

@@ -132,19 +132,19 @@ function sparqlUpdate(filename, targetURI, text, callback) {
132132
// Must parse relative to document's base address but patch doc should get diff URI
133133
patchObject = $rdf.sparqlUpdateParser(text, patchKB, patchURI);
134134
} catch(e) {
135-
return callback({
135+
return callback(new HttpError({
136136
status: 400,
137137
message: "Patch format syntax error:\n" + e + '\n'
138-
});
138+
}));
139139
}
140140
debug("PATCH -- reading target file ...");
141141

142142
fs.readFile(filename, { encoding: 'utf8'}, function(err, dataIn) {
143143
if (err) {
144-
return callback({
144+
return callback(new HttpError({
145145
status: 404,
146146
message: "Patch: Original file read error:" + err
147-
});
147+
}));
148148
}
149149

150150
debug("PATCH -- File read OK "+dataIn.length);
@@ -153,10 +153,10 @@ function sparqlUpdate(filename, targetURI, text, callback) {
153153
try {
154154
$rdf.parse(dataIn, targetKB, targetURI, targetContentType);
155155
} catch(e) {
156-
return callback({
156+
return callback(new HttpError({
157157
status: 500,
158158
message: "Patch: Target " + targetContentType + " file syntax error:" + e
159-
});
159+
}));
160160
}
161161
debug("PATCH -- Target parsed OK ");
162162

@@ -165,21 +165,21 @@ function sparqlUpdate(filename, targetURI, text, callback) {
165165

166166
targetKB.applyPatch(patchObject, target, function(err){
167167
if (err) {
168-
return callback({
168+
return callback(new HttpError({
169169
status: 409,
170-
message: err
171-
});
170+
message: err.message
171+
}));
172172
}
173173
debug("PATCH -- Patched. Writeback URI base " + targetURI);
174174
var data = $rdf.serialize(target, targetKB, targetURI, targetContentType);
175175
// debug("Writeback data: " + data);
176176

177177
fs.writeFile(filename, data, {encoding: 'utf8'}, function(err, data) {
178178
if (err) {
179-
return callback({
179+
return callback(new HttpError({
180180
status: 500,
181181
message: "Failed to write file back after patch: "+ err
182-
});
182+
}));
183183
}
184184
debug("PATCH -- applied OK (sync)");
185185
return callback(null, patchKB);

‎lib/handlers/post.js‎

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ var patch = require('./patch.js');
1313

1414
var ldpVocab = require('../vocab/ldp.js');
1515
var rdfVocab = require('../vocab/rdf.js');
16+
var HttpError = require('../http-error');
1617

1718
function handler(req, res, next) {
1819
var ldp = req.app.locals.ldp;
@@ -38,12 +39,12 @@ function handler(req, res, next) {
3839
contentType != 'application/nquads' &&
3940
contentType != 'application/n-quads') {
4041
debug("POST -- Invalid Content Type: " + contentType);
41-
var contentErr = new Error();
42-
contentErr.status = 415;
43-
contentErr.message = "Invalid Content Type";
44-
return next(contentErr);
45-
}
4642

43+
return next(new HttpError({
44+
status: 415,
45+
message: "Invalid Content Type"
46+
}));
47+
}
4748

4849
var containerPath = utils.uriToFilename(req.path, ldp.root);
4950
debug("POST -- Container path: " + containerPath);
@@ -52,10 +53,11 @@ function handler(req, res, next) {
5253
if (containerPath[containerPath.length - 1] != '/') {
5354
debug("POST -- Requested resource is not a container");
5455
res.set('Allow', 'GET,HEAD,PUT,DELETE');
55-
var allowErr = new Error();
56-
allowErr.status = 405;
57-
allowErr.message = "Requested resource is not a container";
58-
return next(allowErr);
56+
57+
return next(new HttpError({
58+
status: 405,
59+
message: "Requested resource is not a container"
60+
}));
5961
}
6062

6163
debug("POST -- Content Type: " + contentType);
@@ -72,10 +74,11 @@ function handler(req, res, next) {
7274
if (resourcePath === null) {
7375
ldp.releaseResourceUri(resourcePath);
7476
debug("POST -- URI already exists or in use");
75-
var resourceErr = new Error();
76-
resourceErr.status = 400;
77-
resourceErr.message = "URI already exists or in use";
78-
return next(resourceErr);
77+
78+
return next(new HttpError({
79+
status: 400,
80+
message: "URI already exists or in use"
81+
}));
7982
}
8083

8184
// Creating a graph and add the req text
@@ -97,7 +100,10 @@ function handler(req, res, next) {
97100
debug("POST -- Error parsing resource: " + parseErr);
98101
ldp.releaseResourceUri(resourcePath);
99102
parseErr.status = 400;
100-
return next(parseErr);
103+
return next(new HttpError({
104+
status: 400,
105+
message: "Error parsing resource"
106+
}));
101107
}
102108

103109
// Add header link to the resource
@@ -122,24 +128,19 @@ function handler(req, res, next) {
122128

123129
function containerCallback(err) {
124130
if (err) {
125-
debug("POST -- Error creating new container: " + err);
126-
var createErr = new Error();
127-
createErr.status = 500;
128-
createErr.message = "Cannot create new container";
129-
return next(createErr);
131+
debug("POST -- Error creating new container: " + err.message);
132+
return next(err);
130133
}
134+
131135
debug("POST -- Created new container " + resourceBaseUri);
132136
res.set('Location', resourceBaseUri);
133137
return res.sendStatus(201);
134138
}
135139

136140
function resourceCallback(err) {
137141
if (err) {
138-
debug("POST -- Error creating resource: " + err);
139-
var createErr = new Error();
140-
createErr.status = 500;
141-
createErr.message = "Cannot create new container";
142-
return next(createErr);
142+
debug("POST -- Error creating resource: " + err.message);
143+
return next(err);
143144
}
144145
res.set('Location', resourceBaseUri);
145146
return res.sendStatus(201);

0 commit comments

Comments
 (0)