Skip to content

Commit

Permalink
Wrapping native mongoldb errors. Specifically duplicate key errors. (#92
Browse files Browse the repository at this point in the history
)

* Wrapping native mongoldb errors. Specifically duplicate key errors. Closes #67

* adding guard in test for false pass

* missing index in test pet model
  • Loading branch information
ekryski authored Jun 21, 2016
1 parent b4934ba commit 297d30a
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/error-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import errors from 'feathers-errors';
export default function errorHandler(error) {
let feathersError = error;

if (error.constructor.name === 'MongooseError' && error.name) {
if (error.name) {
switch(error.name) {
case 'ValidationError':
case 'ValidatorError':
Expand All @@ -18,6 +18,14 @@ export default function errorHandler(error) {
case 'DivergentArrayError':
feathersError = new errors.GeneralError(error);
break;
case 'MongoError':
if (error.code === 11000) {
feathersError = new errors.BadRequest(error);
}
else {
feathersError = new errors.GeneralError(error);
}
break;
}
}

Expand Down
10 changes: 10 additions & 0 deletions test/error-handler.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,14 @@ describe('Feathers Mongoose Error Handler', () => {
done();
}).catch(done);
});

it('wraps a DuplicateKey error as a BadRequest', done => {
let e = Error('Mock Duplicate Key Error');
e.name = 'MongoError';
e.code = 11000;
errorHandler(e).catch(error => {
expect(error).to.be.an.instanceof(errors.BadRequest);
done();
}).catch(done);
});
});
10 changes: 10 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,16 @@ describe('Feathers Mongoose Service', () => {
done();
});
});

it('returns a BadRequest when unique index is violated', function(done) {
pets.create({ type: 'cat', name: 'Bob' })
.then(() => pets.create({ type: 'cat', name: 'Bob' }))
.then(() => done(new Error('Should not be successful')))
.catch(error => {
expect(error.name).to.equal('BadRequest');
done();
});
});
});

describe('Lean Services', () => {
Expand Down
2 changes: 1 addition & 1 deletion test/models/pet.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const Schema = mongoose.Schema;

const PetSchema = new Schema({
type: {type: String, required: true},
name: {type: String, required: true}
name: {type: String, required: true, unique: true}
});

const PetModel = mongoose.model('Pet', PetSchema);
Expand Down

0 comments on commit 297d30a

Please sign in to comment.