0

I build a server with node.js and Express.

Everything works great, but in some cases the client sends invalid parameter, that I don't predict, and I don't handle with. The result of these requests that my server failed, and can't serve other requests.

For example, In one of my function. I have the next lines:

            app.post("/getFile", function (req,res){
            // some code...
              fs.read(fd, buffer, 0, byteRoRead, start, function(err, bytesRead, buffer){
                  buffer.pipe(res);
               }) 
             })

Because the client sent incorrect start param, my server failed with the next error:

fs.js:457
  binding.read(fd, buffer, offset, length, position, wrapper);
          ^
Error: Offset is out of bounds

So now I can fix it, but there is many other error that I can't predict, so I want to gives a client response of unexpected error, but I want that my server would still alive.

3
  • It looks like you have a syntax error - function req,res){. Commented Jun 23, 2014 at 11:15
  • @Scimonster: I correct it - In my source code, the syntax is OK. I didn't copy it correctly. but the question is general. Commented Jun 23, 2014 at 11:17
  • @BenFortune: Thanks Ben, I already fix it. But my question was more general: How can I identify this unexpected error, and send appropriate response to the client. I don't want that my server will shut down every time the client send unexpected parameter. Commented Jun 23, 2014 at 12:01

1 Answer 1

1

Express has built in error handling as a middleware. See http://expressjs.com/guide.html#error-handling for a more comprehensive guide but as an example:

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.send(500, 'Something broke!');
});

This middleware would catch the error, log it to the console and return a 500 page to the user. This also will stop the server crashing. If you wanted to log the error, but still let the server crash add throw err; to the body of that function.

This is sometimes a good idea as you may not want the server to continue to serve requests if it is in some unexpected error state. Refer to http://shapeshed.com/uncaught-exceptions-in-node/ as a good brief guide on the subject. Also, see http://www.joyent.com/developers/node/design/errors for a more detailed discussion.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.