`switch statement for handling different HTTP status codes`

I'm trying to implement a switch statement that returns an error message based on the http status code. Here's what I have so far:

switch(true){
    case err.status.test(/^4/): // 4xx
       res.fail(err.status, err);
       break;
    case err.status.test(/^5/): // 5xx
       res.error(err.status, err.message, {data: err});
       break;

Can someone confirm if my regex is correct for this task?

Answer №1

test() is a method specifically for RegExp, so the correct usage would be:

case /^4/.test(err.status):

In my opinion, relying on switch(true) { ... } can lead to confusion in code readability. I prefer the following approach:

switch(Math.floor(err.status/100)) {
    case 4:
       res.fail(err.status, err);
       break;
    case 5:
       res.error(err.status, err.message, {data: err});
       break;
}

Answer №2

Creating an error object can be a helpful strategy, with keys representing the status code and values for their respective error/success messages.

errorList = {1: 'Informational responses', 2: 'Success', ...}
console.log(errorList[Math.floor(err.status/100)])

This approach often achieves the desired outcome using fewer lines of code.

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

Best practice for retrieving the $scope object inside the ng-view directive

Check out my plunk. Incorporating ngRoute into my project. I want to increase a value using ng-click, and upon clicking "Show total", the ng-view template should display the updated value. However, it seems like the scope is not being accessed as expecte ...

What could be causing the issue of $.ajax being undefined while utilizing jQuery in Node.js?

I'm currently testing a module on Node.js that is meant for client-side use. In order to make $.ajax work, I need some guidance. To begin with, I have installed jQuery on the project using: $ npm install jQuery Despite this, when I try to access $. ...

Can local storage be accessed within a function and utilized during the Windows.onload event?

I have an onclick function that dynamically returns 'x' and stores it in a div. However, after a page refresh, the dynamic div resets and the data is lost. To prevent this, I stored the data in local storage within the 'test' function a ...

What is the best method for submitting information using AJAX and jQuery?

Here is the HTML code in question: <script src='https://code.jquery.com/jquery-1.12.4.min.js'></script> <p>1</p> <!-- this content gets loaded with <?php echo $item->id; ?> --> <a id='delBtn1' ...

Adjusting the view of an OpenLayers3 map to encompass various vector layers

My OpenLayers3 map includes an OSM Tile layer and one or more Vector layers. I have a function that allows me to zoom into a single layer successfully: vector.addEventListener("change", function() { map.getView().fitExtent(vectorSource.getExtent(), ma ...

The child component notifies the parent to update itself, then the parent proceeds to update the input value of another child

This question may have been asked numerous times before, but despite trying various approaches such as using a subscription on the child component and ngOnChanges, I am still unable to get it to work. Here is the basic structure of the issue in my project ...

Tips for retrieving the output from an Azure Function

Just getting started with Azure Functions and I have this code snippet: module.exports = function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); context.log(context.req.body.videoId) ...

I'm struggling to understand why the jQuery find() method isn't functioning as expected

UPDATE: In a twist of events not caused by syntax errors, but rather by a loading issue with the html template, it turns out that the checkbox update was happening prematurely. So if you're searching for an element that seems to be missing, it may sim ...

Running Jasmine asynchronously in a SystemJS and TypeScript setup

I am currently executing Jasmine tests within a SystemJS and Typescript environment (essentially a plunk setup that is designed to be an Angular 2 testing platform). Jasmine is being deliberately utilized as a global library, rather than being imported vi ...

Show only the selected option with jQuery's on change event and disable or remove the other options

My goal is to make it so that when a user selects an option from a dropdown menu, the other options are disabled or hidden. For example, if option "1" is selected, options "2", "3", and "4" will be removed: <div class="abc"> <div class="xyz"> ...

Refreshing a value in the view at regular intervals using a filter in Vue

Trying to create a countdown timer with vue, but the view is not updating. Here are my app.js and index.html: var nowDate = new Date; var nextNewYearsEve = new Date(nowDate.getFullYear(), 11, 31, 23, 59, 59, 59); var timeLeftToNewYearsEve = nextNewYears ...

Modifying an image on a website with XML information and jQuery

I'm in the process of revamping my website's HTML structure and switching to using an XML file for content. The jQuery script I have is as follows: <script> function extractSiteName() { var URL = window.location.href; var das ...

What is the best way to implement a timeout feature in Vue after a button is clicked?

I am struggling to make the background color return to its default after 3 seconds using the setTimeout method. How can I adjust my code to achieve this successfully, or should I consider using a transition instead? <div id="exercise"> <di ...

Upon completion of the user registration process, the req.isAuthenticated method is showing a false

I've encountered this issue in a few of my previous apps and I'm unsure what's causing it. When I navigate to the login page and successfully log in a user, everything works as expected and I have access to the logged-in user. However, when ...

Refresh the data in an existing Highstock chart with JavaScript only

I'm currently updating a website and unfortunately, I do not have access to the original code. All I am able to do is append new code at the end of it. The existing code consists of a highstock chart with specific data attributes. Here is the snippet ...

Looping through color transitions upon hover using CSS

I am trying to create a color transition effect on hover, where the background changes from yellow to red and then back to yellow in a loop. I'm having trouble figuring out how to make this transition repeat continuously. Do I need to incorporate Java ...

Is there a way to only allow the active video to play while disabling the others in this Vue 3 and Bootstrap 5 carousel?

I'm currently developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Additionally, I'm incorporating Bootstrap 5 for the UI. To showcase movie trailers on the movie details page, I've created the ...

What is the reason behind the "Error [ERR_HTTP_HEADERS_SENT]" being triggered by using "return next()"?

I built a custom Dialogflow chatbot designed to handle currency conversions. In my fulfillment code, I am utilizing an API to execute the conversion based on user input. However, I encountered an "Error [ERR_HTTP_HEADERS_SENT]" message when using "return n ...

An effective method for excluding null values with an Angular pipe

I am currently working on an Angular pipe that filters results based on user input. The problem I'm encountering is that some of the results do not have a value, resulting in this error message: Cannot read property 'toLocaleLowerCase' o ...

Using jQuery to send a POST request with a data object

Trying to figure out something. Attempting to post an object using jQuery Ajax POST, like so: var dataPostYear = { viewType:GetViewType(), viewDate:'2009/09/08', languageId:GetLanguageId() }; $.ajax({ type: "POST", url: url ...