0

If I send a valid fetch api query to this Express server it works fine. If I send an invalid query the server crashes (ReferenceError: next is not defined). How can I change this so that if an error occurs;

  1. the server does not crash
  2. the client receives an error message from the server

Express server.js:

// Add a new test-resource-a
app.post('/test-resource-a', (request, response) => {
    pool.query('INSERT INTO my_table SET ?', request.body, (error, result) => {
        if (error) {
            next(err);
        }
        response.status(201).send(`test-resource-a added with id: ${result.insertId}`);
    });
});

//An error handling middleware
app.use(function (err, req, res, next) {
    res.status(500);
    res.send("Oops, something went wrong.")
});

1 Answer 1

1

This error is mean the next method is not define. In your case, I think you don't need the next method.

// Add a new test-resource-a
app.post('/test-resource-a', (request, response) => {
    pool.query('INSERT INTO my_table SET ?', request.body, (error, result) => {
        if (error) {
            response.status(400).send(err);
        } else {
            response.status(201).send(`test-resource-a added with id: ${result.insertId}`);
        }
    });
});

//An error handling middleware
app.use(function (err, req, res, next) {
    res.status(500);
    res.send("Oops, something went wrong.")
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Manlok - works great! (err should be error but I ended upp changing it to 'There was an error' to avoid sending sensitive db info to the client). Not sure what the 'middleware' is needed for so I removed it. I suppose that like this all errors will be shown as '400 (Bad Request)'? What if I want to give more detailed error messages to the client - do I just add an if/else statement in the same place with different error messages?
you can revise your query to check more condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.