0

how can I catch an error in NodeJS or create own error code and send it to the frontend to inform the user? In the following code I am looking into the database result if there were any data deleted and try to send an error code. How can I send the error code to my react frontend? Maybe using response.json("Not deleted any user"). Tried it already out. How can I prevent my server from crashing? If the sql is not correcting because there was no id send to delete it is crashing. Thanks for the answers for this two cases.

db.getConnection((err, connection) => {
      if (err) throw err;
      connection.query(
        "DELETE FROM users where users_id = ?",
        [2],
        (err, rows) => {
          connection.release();
          if (rows.affectedRows == 0) {
            throw err;
          }
          if (err) throw err;
          if (!err) {
            res.redirect("/");
          } else {
            console.log(err);
          }
          console.log("Daten gelöscht", rows.affectedRows);
        }
      );
    });
7
  • are you using express? Commented Nov 18, 2021 at 21:47
  • yes i am using express Commented Nov 18, 2021 at 21:56
  • expressjs.com/en/guide/… Commented Nov 18, 2021 at 22:00
  • How can I retrieve the message at the frontend? When I am using following line of code: return res.status(500).send("Something broke!"); Commented Nov 18, 2021 at 22:29
  • 1
    Error codes are standard to define something specific client errors( 400 -499), server errors(500-599) and so on if you want to return something you should use status 200 to tell that server responded successfully(but error was somethng else which you will pass in that response) and then in frontend just call function to show what was the problem Commented Nov 18, 2021 at 22:39

1 Answer 1

1

You should use a try, catch block. If you want to throw a custom exception, you can do something like

throw new NotFoundException("Record with the given id Not Found...!!!"):

I use it in nestjs I am not fully sure that this will work for you but you can try :)

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

Comments

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.