Thanks for your quick answers. I think I have to split my question in two
parts:
1.)
If an error occured, the controller can send the response to the client.
But, as Martin wrote, the middleware is able to catch an err via
function(err, req, res, next). We wouldn't need this feature, if the
controller would send always the response. I think the "catch-error"
middleware function is useful to log error details etc.
e.g.:
server.get(/foo,
[
controller.foo,
controller.bar,
controller.catchError
]
);
No errors: router -> controller.foo -> controller.bar -> response to client
Error in foo(): router -> controller.foo -> controller.catchError (gets
error object from foo's next(err)) -> log details and send response
Please correct me if I am wrong!
2.)
If (1) is correct and I should use a middleware "catch-error" function:
Can you please give me an (error and success) example how to use next(), if
the controller runs a callback function?
e.g.:
// controller function
exports.foo = function controllerFoo(req, res, next) {
model.getFileData("/tmp/foo.txt", function readMyFile(err, data) {
if(err) {
console.log("error while reading file");
return(next(new Error()); // doesn't work because return exits
readMyFile() and NOT controllerFoo()
}
console.log("success");
// do something with data
});
return(next()); // doesn't work because next() will be called before
reading the file
}
Thanks a lot for your help.
On Monday, September 17, 2012 9:31:15 PM UTC+2, José F. Romaniello wrote:
>
> The problem I see is that you car calling next() before you finish reading
> the file.
>
> But, I dont understand why you want to let know to the next middleware
> that this one has fail?
>
> I havent seen that a lot.. For instance lot of authentication code do
> something along these lines:
>
> function addUserToRequest(req, res, next) {
> getUser(req.session.userId, function foo(err, user) {
> if(err) {
> return res.send(401); ///respond with unauthorized and do not call
> the next middleware.
> }
> req.user = user; //put the user in the request object so the next
> middleware can use it
> next(); //call the next middleware.
> });
> }
>
>
> 2012/9/17 Aga <[email protected] <javascript:>>
>
>> exports.controller = function controller(req, res, next) {
>> model.getFileData("/tmp/foo.txt", function foo(err, data) {
>> if(err) {
>> console.log("error while reading file");
>> return(next(new Error()); *// exits foo() and NOT controller()*
>> }
>> console.log("success");
>> // do something with data
>> });
>> return(next());
>> }
>>
>
>
--
Job Board: http://jobs.nodejs.org/
Posting guidelines:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en