Skip to content

Commit b9d1f25

Browse files
author
Oliver Rumbelow
committed
Merge pull request holidayextras#15 from holidayextras/better-errors
Wrap mongo errors with json:api formatting
2 parents d953287 + 22a8fe5 commit b9d1f25

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

lib/mongoHandler.js

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,15 @@ MongoStore._notFoundError = function(type, id) {
100100
};
101101
};
102102

103+
MongoStore._unknownError = function(err) {
104+
return {
105+
status: "500",
106+
code: "EUNKNOWN",
107+
title: "An unknown error has occured",
108+
detail: err
109+
};
110+
};
111+
103112

104113
MongoStore.prototype._createIndexesForRelationships = function(collection, relationshipAttributeNames) {
105114
var index = relationshipAttributeNames.reduce(function(partialIndex, name) {
@@ -212,7 +221,10 @@ MongoStore.prototype.search = function(request, callback) {
212221
return collection.find(criteria, { _id: 0 }).count(asyncCallback);
213222
}
214223
}, function(err, results) {
215-
return callback(err, results.resultSet, results.totalRows);
224+
if (err) {
225+
return callback(MongoStore._unknownError);
226+
}
227+
return callback(null, results.resultSet, results.totalRows);
216228
});
217229
};
218230

@@ -242,7 +254,7 @@ MongoStore.prototype.create = function(request, newResource, callback) {
242254
var document = MongoStore._toMongoDocument(newResource);
243255
debug("insert", JSON.stringify(document));
244256
collection.insertOne(document, function(err) {
245-
if (err) return callback(err);
257+
if (err) return callback(MongoStore._unknownError(err));
246258
collection.findOne(document, { _id: 0 }, callback);
247259
});
248260
};
@@ -255,11 +267,11 @@ MongoStore.prototype.delete = function(request, callback) {
255267
var collection = this._db.collection(request.params.type);
256268
var documentId = MongoStore._mongoUuid(request.params.id);
257269
collection.deleteOne({ _id: documentId }, function(err, result) {
258-
if (err) return callback(err);
270+
if (err) return callback(MongoStore._unknownError(err));
259271
if (result.deletedCount === 0) {
260272
return callback(MongoStore._notFoundError(request.params.type, request.params.id));
261273
}
262-
return callback(err, result);
274+
return callback(null, result);
263275
});
264276
};
265277

@@ -283,7 +295,7 @@ MongoStore.prototype.update = function(request, partialResource, callback) {
283295
}, function(err, result) {
284296
if (err) {
285297
debug("err", JSON.stringify(err));
286-
return callback(err);
298+
return callback(MongoStore._unknownError(err));
287299
}
288300

289301
if (!result || !result.value) {

0 commit comments

Comments
 (0)