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