how to catch errors in express.get in node.js express? (throw err; // Rethrow non-MySQL errors) on express.get/app.get

Viewed 35

Updated:

I am using express js and mysql for my react app. The code is working well when I am selecting a data that is registered in the database but everytime I select a non existing data it throws an error

throw err; // Rethrow non-MySQL errors

this is my code

const express = require('express');
const app = express();
const mysql = require('mysql');

app.use(express.json());

app.get('/api/get',(req,res)=>{
    const sql = "SELECT * FROM user WHERE email = 'not_exist';"
    db.query(sql,(err, result)=>{
        console.log(result[0].email);
        res.send(result);
    })
})


app.listen(3001, ()=>{
    console.log('The server has started');
});

I want the server to send null when there is the data does not exist.

1 Answers

I have resolved it by just removing console.log(result[0].email). Because the email is not defined when the result is null.

app.get('/api/get', (req,res) => {
  const sql = "SELECT * FROM user WHERE email = 'not_exist';"
  db.query(sql, (err, result) => {
    res.send(result);
  })
})

To catch the error I just used the try/catch

app.get('/api/get',(req,res) => {
  const sql = "SELECT * FROM user WHERE email = 'not_exist';"
  db.query(sql, (err, result) => {
    try {
      console.log(result[0].email);
      res.send(result);
    } catch(ex) {
      res.send('not registered');
    }
  })
})
Related