Pattern for handling errors in an efficient and streamlined manner

Currently, I am exploring the use of Express for developing a basic JSON API. However, I have concerns about how to effectively manage input parameter validation and error handling in my project. Errors can occur during both the validation process and when accessing the database. Here's the current structure:

router.use(function(req, res, next) {
    validate(req.query).then(function() {
        next()
    }).catch(function(e) {
        next(e)
    })
})

router.get("/", function(req, res, next) {
    someDatabaseAccess(req.query).then(function(results) {
        res.json(results)
    }).catch(function(e) {
        next(e)
    })
})

router.use(function(e, req, res, next) {

    // ... (handling specific errors)

    res.status(400)
    res.json(someDummyResponse(e))
})

The validation process is defined as follows:

const validate = function(q) {
    return new Promise(function(resolve, reject) {
        if (q.someParameter) {
            if (somethingWrong(q.someParameter)) {
                reject(new Error("Something wrong!"))
            }
        }
        resolve()
    })
}

Do you think this approach is logical? Are there any suggestions on how I could improve or simplify it?

Answer №1

For validation purposes, I recommend using tools like JSONSchema. One of the options is to utilize a package such as tv4 for validation, although there are numerous similar tools available. Begin by creating a schema for the object:

const tv4 = require('tv4');

const schema = {
  type: object,
  properties: {
    name: string,
    phone: string
  },
  required: ['name']
};

In your route implementation, include the following:

app.post('/someroute', (req, res, next) => {
  if (!tv4.validate(req.body, schema)) 
    return next(new Error('not valid input'));
  // Perform necessary operations here
  res.end();
});

When it comes to error handling in Express, you can add a middleware function at the end with additional parameters:

// Add middleware
app.use(bodyParser.json())

// Add custom middleware
app.use(function(req, res, next) {
  // Implement necessary functionality
  next();
});    

// Define routes
app.get('/', () => {})

// Ensure that the error handler is always placed last
// Pay attention to the additional `err` parameter
app.use(function (err, req, res, next) {
  if (err) {
    // Log errors or handle exceptions accordingly
  }
  else next();
});

Answer №2

To enhance the organization of your application, consider creating a dedicated error configuration file and utilizing a middleware to handle errors. This approach will improve the overall structure of your app.

Error.json

"err":[
   "errorLog501":{
     "status":501,
     "message":"request is invalid"
    }
]

`

var errCodes = require('./error.json')
var errMiddleware = function(req, res, next) {
   if (req.body.hello) {
   // some cool stuff
     res.json(errCodes.errorLog501)
   } else {
     next();
   }
}

app.use(errMiddleware); //the middleware is invoked for every request made

It is crucial to include status codes in the JSON response for effective error handling on the frontend, ensuring users are informed about the application's current state.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Slick slider issue: Unexpected TypeError - the slick method is undefined for o[i]

I'm facing an issue where, upon clicking the search button, I want the previous search results to clear and new ones to be displayed. However, this action triggers a slick slider error, causing all items to align vertically instead of in the intended ...

Retrieve the current element's 'this' object even after binding an external 'this' object

Is the title of this question confusing? Let's dive in. Imagine you have something like this: var Test = function(){ this.foo = a; } Test.prototype.init = function() { $(document).on('change', '.form-control', this.myFun ...

Node.js put method fails to properly update the model in the database

Even though the code runs without any errors in the console, the field 'check' still doesn't change to true state. Why could this be happening? apiRoutes.put('/intake/:id', function(req, res) { var id = req.params.id; Intake. ...

Excessive JSON formatting is consuming an excessive amount of storage space

As I work on developing a website that recommends locations to visit in NYC, I am facing an issue with saving JSON data in local storage. My goal is to allow users to add their own suggestions and eventually integrate MongoDB into the site. To build the si ...

Troubleshooting a JavaScript error while attempting to execute a function from a

I have been working on a new JavaScript library named TechX. Check out the code snippet below: (function(){ function tex(s){ return new tex.init(s); }; //initiate the init selector function tex.init = function(s ...

UI-Router: What is the best way to access a page within my project without adding it as a State?

Currently in the process of learning Angular and UI-Router. Initially, I followed the advice of many and chose to utilize UI-Router. In my original setup, the login page was included in all States. However, I decided it would be best to keep it as a separ ...

Establishing a connection between client and server in a Node.js application

Exploring the intricacies of CORS in a node.JS application while revisiting the fundamental client-server concept has raised an intriguing question for me. Let's start with the server-side code: const express = require('express'), ser ...

Recently updated to the latest versions of Angular, AngularCLI, and Rxjs (version 6), however encountering an error stating "Property 'take' does not exist on type 'Observable'"

Recently, I made the decision to update my Angular5 project to Angular6 and upgraded all dependencies along with it (such as rxjs now at version 6 and angular-cli). However, I have encountered a problem that is proving difficult to resolve: ERROR in src/ ...

Working with promises and Async/Await in Express/node can sometimes feel ineffective

Currently, I am delving into the world of node and express with the aim to create a function that can extract data from a CSV file uploaded by the user. My challenge lies in the fact that the data is being outputted as an empty array before it goes through ...

Encountered an issue while attempting to write to SQLite, error code 6 is

I'm working on a project that involves writing to a SQLite Database from a cross-platform app built with AngularJS, Monaca, and Onsen UI. Within my app, there's a view where users input their username and password. I store these details in a Ser ...

Leveraging ES6 Generators for Efficient XMLHttpRequests

My goal is to simplify AJAX calls using ES6 generators, but I've encountered some issues: let xhr = new XMLHttpRequest() function *statechange() { yield xhr.readyState; } let gen = statechange(); xhr.open("GET", myUrl, true); xhr.onreadystatec ...

proper integration of socket.io

I have been experimenting with socket io for my project to display online friends, and I have noticed an issue that seems strange to me. Every time the page is rerendered (whether due to a user changing their profile information or sending a friend request ...

Manipulating JSON data fetched through AJAX beyond the success callback

I'm facing an issue with storing JSON data received via AJAX in an external variable for future use. I came across this answer on Stack Overflow (load json into variable), which provided some basic insights, but it seems like I might be missing someth ...

What is the correct way to implement photo loading using Node and Webpack?

When it comes to loading photos in node, should I use relative paths or file URLs? And how can I properly load photos from their relative path? At the moment, I am using express to serve static files: server.use(express.static(__dirname + '/../publi ...

"Implementing the Three.js OBJloader feature with the enhanced functionality of

I'm looking to create a simple 3D model viewer with rotation capabilities, but I've run into an issue. When I add OrbitControls to my code, the page just shows up as blank: controls = new THREE.OrbitControls( camera ); controls.addEventListener( ...

Notify any errors that arise during the project

In my project, it is crucial to notify developers whenever an error occurs (e.g. unable to fetch user from database, undefined variable x, myfun() not a function, etc.) The technology stack we are using includes: NODE for backend language Express for r ...

Using props in the v-bind:src directive with Vue - a comprehensive guide!

I have a Vue application with a Block component that needs to display an image. The Block component is used multiple times in the App component, each time passing a value to determine which image src to choose from an array. When I try to print {{ this.Im ...

The use of HTML in the static folder of NodeJS may lead to issues when loading assets using relative paths

For my NodeJS website, I have a static folder setup. What's interesting is that even though the files are stored in the folder, I still need to specify the path to it in the index.html file. When I include the folder name in the path, it works fine o ...

Problems with Ajax functionality

Excuse my rusty JavaScript skills but I'm attempting to use an AJAX call to a PHP file, pass it a plan type, and then determine if there are enough available slots for the plan. If so, return true; otherwise, false. Below is the Form in XHTML: <fo ...