Skip to content

Commit

Permalink
Merge pull request #232 from flyvictor/PO-2906-create-resource-catch
Browse files Browse the repository at this point in the history
fix(PO-2906): send error if after write hook throws an error
  • Loading branch information
EugeneKostrikov authored Nov 9, 2021
2 parents 40b5e87 + 8ec3a64 commit ce7a773
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
11 changes: 9 additions & 2 deletions lib/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,11 @@ function route(name, model, resources, inflect, querytree, metadataProviders, zi
})
.then(function(mappedMainResources){
return createResources(model, mappedMainResources);
}).then(respond);
})
.then(respond)
.catch(function(error) {
sendError(req, res, 500, error);
});

}else{
runBefores(model.modelName, mainResources)
Expand All @@ -363,7 +367,10 @@ function route(name, model, resources, inflect, querytree, metadataProviders, zi
.then(function(resources){
return createResources(model, resources)
})
.then(respond);
.then(respond)
.catch(function(error) {
sendError(req, res, 500, error);
});
}

function flattenLinks(resources){
Expand Down
13 changes: 11 additions & 2 deletions test/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,17 @@ module.exports = function(options, port) {
};
}
}])
.afterWrite([{
name: "throw-error",
init: function(){
return function(req, res){
if (req.headers['throw-after-write-error']) {
throw Error('after write error');
}
return this;
};
}
}])

//Hooks with standard config defined in personHooks.js
.beforeWrite([personHooks.beforeWrite])
Expand Down Expand Up @@ -467,5 +478,3 @@ module.exports = function(options, port) {

return app;
};


12 changes: 12 additions & 0 deletions test/fortune/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,18 @@ module.exports = function(options){
});
});
});
it("after write hook throws an error on resource creating", function(done) {
request(baseUrl).post('/people')
.set('content-type', 'application/json')
.send(JSON.stringify({people: [
{email: 'testing'}
]}))
.set('throw-after-write-error', true)
.end(function(err, res){
res.statusCode.should.equal(500);
done();
});
});

});
describe('onResponseSend hooks', function(){
Expand Down

0 comments on commit ce7a773

Please sign in to comment.