Reputation: 2272
I was wondering what's the best practice and if I should create:
Upvotes: 2
Views: 169
Reputation: 1935
A neat way of going about this would be to simply add the errors as custom responses under api/responses
. This way even the invocation becomes pretty neat. Although the doc says you should add them directly in the responses
directory, I'm sure there must be a way to nest them under, say, responses/errors
. I'll try that out and post an update in a bit.
Alright, off a quick search, I couldn't find any way to nest the responses, but you can use a small workaround that's not quite as neat:
Create the responses/errors
directory with all the custom error response handlers. Create a custom response and name it something like custom.js
. Then specify the response name while calling res.custom()
.
I'm adding a short snippet just for illustration:
api/responses/custom.js:
var customErrors = {
customError1: require('./errors/customError1'),
customError2: require('./errors/customError2')
};
module.exports = function custom (errorName, data) {
var req = this.req;
var res = this.res;
if (customErrors[errorName]) return customErrors[errorName](req, res, data);
else return res.negotiate();
}
From the controller:
res.custom('authError', data);
If you don't need logical processing for different errors, you can do away with the whole errors/
directory and directly invoke the respective views from custom.js
:
module.exports = function custom (viewName, data) {
var req = this.req;
var res = this.res;
return res.view('errors/' + viewName, data);//assuming you have error views in views/errors
}
(You should first check if the view exists. Find out how on the linked page.)
Although I'm using something like this for certain purposes (dividing routes and so on), there definitely should be a way to include response handlers defined in different directories. (Perhaps by reconfiguring some grunt task?) I'll try to find that out and update if I find any success.
Good luck!
Update
Okay, so I found that the responses
hook adds all files to res
without checking if they are directories. So adding a directory under responses
results in a TypeError
from lodash
. I may be reading this wrong but I guess it's reasonable to conclude that currently it's not possible to add a directory there, so I guess you'll have to stick to one of the above solutions.
Upvotes: 2