Should we focus on error handling solely on the server side, or should we also consider implementing it on the script side

Currently, I am developing an NBA statistics application. My project involves multiple routes and database queries distributed across several files, and I find myself uncertain about error handling procedures. Below is the function within my 'mutualScript.js' file that invokes the 'boxScoresTraditional/home/:playerid/:season' route:

FULL GITHUB REPOSITORY:

mutualScript.js:

const getSeasonStatAvgLocal = async(stat, year, playerId, H_or_V) => {
    let url;

    if (H_or_V === 'home') {
        url = '/boxScoresTraditional/home/' + playerId + '/' + year; 
    } else {
        url = '/boxScoresTraditional/visitor/' + playerId + '/' + year; 
    } 
    let gameDetailsArray = await getJsonResponse(url);
    let statTotal = await getSeasonTotalOfStat(stat.toLowerCase(), gameDetailsArray);

    //let gamesPlayed = await getGamesPlayedInSeason(gameDetailsArray);
    let gamesPlayed = gameDetailsArray.length;
    let statAverage = statTotal / gamesPlayed;

    return Number.parseFloat(statAverage).toFixed(2);
}

In the snippet above:

let gameDetailsArray = await getJsonResponse(url);

the function sends the 'boxScoresTraditional/home/:playerid/:season' URL to the 'getJsonResponse' function in the same script. This function performs a fetch call to the respective route, which is located in another file named 'boxScoresTradtionalRoutes.js'. Both these scripts are outlined below:

mutualScript.js:

const getJsonResponse = async (url) => {
    console.log(url);
    const response = await fetch(url);
    try{
        if (response.ok){
            const jsonResponse = await response.json();
            return jsonResponse;
        }
    } catch(err){
        console.log(err);
    }
}

boxScoresTraditionalRoutes.js:

const express = require('express');
const router = express.Router();
const boxScoreTraditional = require('../services/boxscorestraditionalQueries')

/**
 * @swagger 
 * /boxScoresTraditional/home/{playerid}/{season}:
 *   get:
 *     parameters:
 *       - in: path
 *         name: playerid
 *         schema:
 *           type: string
 *         required: true
 *         description: String ID of the player who's box scores we are getting
 *       - in: path
 *         name: season
 *         schema:
 *           type: string
 *         required: true
 *         description: String season of the box scores we are getting
 *     responses:
 *       '200':
 *         description: A successful response
 *       
 */
router.get('/home/:playerid/:season', boxScoreTraditional.getBoxScoreTraditionalHome);

router.get('/visitor/:playerid/:season', boxScoreTraditional.getBoxScoreTraditionalVisitor);

The route then executes the database query defined in 'boxScoresTraditionalQueries.js', as shown below:

const getBoxScoreTraditionalHome = (request, response) => {
    const {playerid, season} = request.params;
 
    let newSeason = JSON.stringify(season);
    let stringSeason = newSeason.replace(/"/g, '');
    db.query(`SELECT * FROM "boxscorestraditional${stringSeason}" 
              INNER JOIN "boxscoresummary${stringSeason}" 
              ON "boxscorestraditional${stringSeason}".game_id = "boxscoresummary${stringSeason}".game_id
              WHERE player_id = $1
              AND "boxscoresummary${stringSeason}".home_team_id = "boxscorestraditional${stringSeason}".team_id
              ORDER BY "boxscorestraditional${stringSeason}".id`, [playerid], (error, results) => {
      if (error) {
         throw error
      }
      response.status(200).json(results.rows)
    })
}

My main dilemma lies in error handling. When encountering issues with the 'getBoxScoreTraditionalHome' function, errors lead to app crashes without proper propagation back to the front-end 'catch' block in 'getJsonResponse'. Even testing this route using Postman promptly crashes the application due to error throwing. Would removing 'if(error){ throw error }' from the backend code and solely relying on 'response.status(200).json(results.rows)' be sufficient, allowing the 'catch' block in 'getJsonResponse' to handle all potential errors?

I appreciate your time and insight into this matter, especially from a novice like me venturing into Node.js development.

Thank you, Jack

While attempting different approaches such as sending errors back from the backend or displaying error messages in Postman, I strive to streamline error management by consolidating it within the 'catch' block of 'getJsonResponse' for all HTTP requests. Considering the significance of server-side error checking, I seek guidance on invoking an error handler middleware from 'boxScoresTraditionalQueries.js'. Here is the segment involving error handling within the database query function:

const getBoxScoreTraditionalHome = (request, response) => {
    const {playerid, season} = request.params;
 
    let newSeason = JSON.stringify(season);
    let stringSeason = newSeason.replace(/"/g, '');
    db.query(`SELECT * FROM "boxscorestraditional${stringSeason}" 
              INNER JOIN "boxscoresummary${stringSeason}" 
              ON "boxscorestraditional${stringSeason}".game_id = "boxscoresummary${stringSeason}".game_id
              WHERE player_id = $1
              AND "boxscoresummary${stringSeason}".home_team_id = "boxscorestraditional${stringSeason}".team_id
              ORDER BY "boxscorestraditional${stringSeason}".id`, [playerid], (error, results) => {
      if (error) {
         throw error
      }
      response.status(200).json(results.rows)
    })
}

Being meticulous about documenting, error-handling, and testing every aspect of this evolving project, I aim to refine one route comprehensively before replicating the implementation for other pathways.

Your assistance is greatly valued. Jack

Answer №1

When it comes to handling errors, there are various approaches you can take. If you are working with Express and a templating engine like pug or hbs, one effective method is using response.render().

For instance, within your if statement, you can try the following snippet:

     return response.render("path/to/view", {
      message: "Page Error!",
    });

This will display a chosen view whenever an error occurs. You can use the same view as the one from which the request originated, while also passing the message variable to the HTML template. The message should contain an error message.

In the corresponding view file, you can then check for this variable. Here's an example using hbs:

{{#if message}}
  <div class="alert alert-danger">
    {{message}}
  </div>
{{/if}}

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

What are the steps to implement THREE.MeshLine in my JavaScript project?

While exploring ways to create a line using three.js with a modified width, I stumbled upon this article suggesting the usage of a THREE.MeshLine class available here. However, when I attempted to follow the documentation to implement it in my script, I en ...

` `issues with fmt:massage tag` `

When I try to update my page elements using ajax, I encountered a problem: the fmt:message tag doesn't work when I set it in javascript. In the JSP page everything works fine: <div id="div"> <fmt:message key="search_select_country"/> & ...

Issue with webpack-dev-server causing it to not reload and build automatically due to configuration error

Currently in my project, I am utilizing the following versions: "webpack": "2.2.1", "webpack-dev-server": "2.4.2" I am looking to create an application that can automatically rebuild when a file is changed using webpack-dev-server live reloading. Within ...

Obtaining asynchronous data with nodejs is possible through several methods

I am currently trying to retrieve data from a MySQL table using Node.js. I have a SQL routine in another Node.js file that I am calling, but I am struggling to get the callback function to return the data. I suspect that the issue may be related to calling ...

Make the jQuery toggle() function work like a regular radio button when selecting multiple options at a time

I have recently created two radio buttons using <i> font icons. Previously, I had successfully used the same code to create a checkbox, so I applied it to the radio buttons as well. After fixing the positioning, everything seemed fine when interactin ...

Reset the input field upon button press

Is there a way to clear the input field after pressing the button? <div class="form-group autocomplete"> <div class="input-group search"> <input id="search" name="searchterm" type="search" class="form-control form-control search-input" pl ...

Emphasizing specific lines using an array

There is a block of text containing multiple lines, each wrapped within a span with an incremented value at the end (like line-1, line-2, line-3, and so on) to distinguish between them. <div id="textbody"> <span id="line-1">what is love< ...

Transferring form data from Jade to Node.js for submission

My Jade template includes the following form structure: form(action='/scheduler/save/' + project.Id, method='post') div.form-group label.control-label.col-md-2 RecurringPattern di ...

Is Webpack capable of adjusting public paths dynamically?

Currently, I have an application running on express js and angular 2. To bundle my modules, I am using webpack and utilizing webpack dev middleware to run webpack with express. In order to serve the index.html file for all routes, I have configured a wild ...

Reconstructing a file from a string using the FileReader in reverse

Converting the file to a string: const reader = new FileReader() reader.readAsText(file, 'UTF-8') reader.onload = (event) => { this.textFile = event.target.result }; Upon uploading a Zip, Text, or Image file, my string appears as: data:t ...

Ajax requests function properly only on one occasion

My select option works perfectly the first time, but then the request does not execute again. I suspect that the issue lies with the 'onchange' event. Here is my Ajax code : jQuery(document).ready(function($) { $('#referenceProduit') ...

Tips for aligning text at the center of a MUI snackbar

I've been attempting to align text in a snackbar center, but so far I haven't had any luck. Can someone please help me with this? Any suggestions or solutions would be greatly appreciated. import Stack from "@mui/material/Stack"; impor ...

The absence of the iframe in ie8 is causing problems that cannot be fixed with relative positioning

On a website, I am integrating an external 2-factor authentication solution called Duo Web using their PHP and Javascript. It works smoothly on all browsers except for IE8. When the user passes the initial login screen, the 2FA login page loads, but the if ...

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

Store Express app session data in Mocha and Supertest for persistent use

I have developed an Express app where JWT is used for authentication, and the token is stored in the session after login. req.session.JWToken = '<token>'; The authentication middleware is as follows: this.use('(^\/admin')& ...

Tips for managing serverside validation and clientside validation in your web application

Utilizing both clientside and serverside validation in ASP.NET controls is crucial for ensuring usability and security. While simple validations like length checks or regular expressions are easy to implement and maintain, more complex validations can beco ...

Troubleshooting: Magento checkout page keeps scrolling to the top

We are experiencing an issue where, during the one page checkout process, the next step is not automatically scrolling to the top of the page when it loads. After a user fills out all their billing information and clicks continue, the next step appears ha ...

Experiencing variations in value with the MUI date picker

I encountered an issue with the Mui 5 date picker. When I change the date using the calendar, I get the expected result. For example, if I select the 26th, I get the following timestamp: "2022-01-26T09:16:10.000Z". However, when I directly edit ...

Array reducer producing unexpected result of NAN

Query I am facing an issue with a specific array and reducer function. The array in question is as follows: let oddsArray = [undefined, undefined, 5, 5] Accompanied by this reducer function: const reducer = (accumulator, currentValue) => accumulator ...

Sending confidential data from the view to the controller without relying on form submission

I am looking for a way to pass a hidden field from a view to a controller. Inside index.chtml <div id="root"> ................ @Html.Hidden("HProjectTypeId", "somevalue") </div> The above code snippet is not enclosed within any form tags ...