Home > other >  How to add a custom error message in Express
How to add a custom error message in Express

Time:09-25

I have created a server application where it can serve dynamic pages depending on the path. Simply, this checks if the path number provided is a prime number or not... For example, localhost:3000/isprime/7 -------> The input parameter 7 is a prime number localhost:3000/isprime/36 -------> The input parameter 36 is not a prime number

The problem is, how can I create an error handler to display an error message if letters are entered into the address instead of digits. For example, localhost:3000/isprime/four

I have very limited knowledge of error handling in the express. Any help would be highly appreciated.

Here's my code so far,

    app.get('/isprime/:inputNumber(\\d )', function(request, response) {
    let num =parseInt(request.params.inputNumber);
  
    function isPrime(num) 
    {
    for(var i = 2; i < num; i  )
    if(num % i === 0) return false;
    return num > 1; 
    }

    if(isPrime(num))
    {
      var p = '<span style="color:blue;">IS a prime number.</span>';
    }
    else
    {
      var p = '<span style="color:red;">IS NOT a prime number.</span>';
    }
  
    let html = ''; 
    html  = '<h1>Prime Number Check</h1>'; 
    html  = '<p>The input parameter <b> '   num  '</b>....'  p  '</p>';
  
    response.send(html); 
    });  

CodePudding user response:

Try to use isNaN(), isNaN() gives a boolean if the number is valid otherwise returns false,

Here is example for your code

app.get('/isprime/:inputNumber(\\d )', function(request, response) {
    let num = parseInt(request.params.inputNumber);
    if(isNaN(num)) {
     response.send("<h1>Invalid number</h1>");
     return; 
    }
    function isPrime(num) {
        for (var i = 2; i < num; i  )
            if (num % i === 0) return false;
        return num > 1;
    }

    if (isPrime(num)) {
        var p = '<span style="color:blue;">IS a prime number.</span>';
    } else {
        var p = '<span style="color:red;">IS NOT a prime number.</span>';
    }

    let html = '';
    html  = '<h1>Prime Number Check</h1>';
    html  = '<p>The input parameter <b> '   num   '</b>....'   p   '</p>';

    response.send(html);
});

CodePudding user response:

The (\\d ) that you're putting at the end of your route definition makes it so that only parameters with 1 or more digits will match the route.

If you remove that, and then isNaN() to test if the parameter value parses to an integer, you will be able to pick out the requests you want and send a response to requests with parameter values that are only letters.

  • Related