Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
NodeJS App crashes when wrong parameters are passed to the API

I have created an CRUD API using typescript NodeJS, Express and MongoDB. What I am trying to achieve is that when using the POST method when I send the correct parameter. API works fine. However whenever I send incorrect parameters to the API the whole NodeJS app crashes, I get an error message in console that the parameters passed to the API are wrong and I will have restart the application again.

When as user sends the incorrect parameters to the API. I don't want the NodeJS app to crash. I want to display the useful error message. Keep the app running. I Don't want to restart the application.

This is the code i use to create New providers.

    public addProviders(req: Request, res: Response, next: NextFunction) {

    var type = req.body.type,
        name = req.body.name;

    let newProvider = new Provider({
        type,
        name
    })

    newProvider.save()
        .then((provider: Object) => {
            if (provider) {
                let statusCode = res.statusCode;
                res.json({
                    statusCode,
                    provider
                })
            }
        })
}

Below is the code that i have tried so far.

        try {
    newProvider.save()
        .then((provider: Object) => {
            if (provider) {
                let statusCode = res.statusCode;
                res.json({
                    statusCode,
                    provider
                })
            }
        })
    }
    catch (e) {
        res.json("enter valid parameters")
    }

I am new to NodeJS. Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to add input validation middleware to check inputs before adding to Database.

#1 You can check it manually, like:

var { type, name } = req.body;

if (typeof type !== 'string') {
    res.status(400).send("type input is not valid");

} else if (typeof name !== 'string') {
    res.status(400).send("name input is not valid");

} else {
    let newProvider = new Provider({
        type,
        name
    })
    // ...rest of the code
}

#2 Or you can use a package like express-validator.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!