Declare the HTTP status code when triggering an error within a service

When one of my services fails, I aim to provide the correct HTTP status code back to the client.

Imagine a basic express app where a service getUserById(userId) {...} is accessed from a controller. This service might fail due to various reasons such as an invalid user id, a bug in the code, or simply because the requested user does not exist. In order to send back the appropriate HTTP status codes (400, 500, and 404), I would need to somehow include them with the error when it's thrown within my service. How can this be achieved and are there any recommended practices? Or maybe I have misunderstood something?

Currently, I handle it like this:

throw { message: 'No user with this ID exists', status: 404 }

However, I do realize that this approach may not be sustainable since it goes against the concept that one should stick to using standard errors only.

Answer №1

To add custom properties to an error object, you can create a new error and then attach the desired properties.

let err = new Error('No user with this ID exists');
err.status = 404;
throw err;

Another approach is to encapsulate this process in a function:

function error(msg, status = 500) {
    let err = new Error('No user with this ID exists');
    err.status = status;
    throw err;
}

You may also opt to create your own subclass of Error:

class MyError extends Error {
    constructor(msg, status = 500) {
        super(msg);
        this.status = status;
    }
}

Then you can use it like so:

throw new MyError('No user with this ID exists', 404);

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

Every time I update the status in the dropdown menu, the corresponding value in the main scope of AngularJS is automatically adjusted

There are four payment statuses available: ALL, PAID, UNPAID, and PARTIALLY_PAID. I need to apply filters based on these payment statuses to display a list of invoices. Scenario 1: When the current payment status is "ALL" and I change it to another sta ...

Uploading files with ASP.NET MVC 3 using a JSON model

I am currently working on a web application that communicates with the server-side (ASP.NET MVC 3) by sending JSON data to specific URLs, without the use of HTML forms. Is there a way for me to send a file to the server and associate it with HttpPostedFil ...

Shopping cart has encountered an issue with storing the data correctly

While I've managed to successfully integrate another service, the challenge now lies in implementing the logic for correctly generating cart items. My goal is to increment the quantity of items in the cart by one with each function call, but it seems ...

Steps for creating interconnected datepickers in jQuery with month and year selection:To create a dependent datepicker with month and year selection using

The JSFiddle I currently have is not functioning as expected. When the user directly selects the end-date, it does not restrict the start-date in this particular fiddle. It should change once the user directly changes the end-date. The functionality works ...

Why isn't v-model functioning properly in Vue?

In my current project involving an API, I encountered a problem. I utilized axios to fetch data from the API, which returned a JSON array. Each array item had a radio value that I appended to it. Despite attempting to use v-model to track changes in the ra ...

code for tracking progress bar on a div using a scroll event listener in vanilla JavaScript

I am currently working on a vertical "progress bar" that will serve as a timeline element. However, I am facing the issue of making it match the height of a specific div rather than the body itself. Despite numerous attempts, I have yet to find a solution ...

Pass JSON data from Laravel to Controller

Recently I started using Laravel 5 and I'm encountering an issue with sending Ajax json data from the view to controller. Here is my routes.php : Route::post('ticket','TicketController@store'); Route::get('ticket', &a ...

One button for two forms to submit

I am looking to use two forms simultaneously. I believe this can be accomplished with the help of ajax. Form1 <form action="upload.php" method="post"> <label for="url">Enter URL:</label> <input type=" ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

iOS is causing issues with the JavaScript function and not allowing it to

By creating an NSString that contains JavaScript, I am able to set the e-mail body. NSString * someString =@"<!DOCTYPE html>\n <html>\n <body> \n <h1>My Web Page</h1> \n <p ...

I'm encountering an issue where the module './src/index.js' cannot be found. The website is functioning properly, but I'm puzzled as to

Whenever I update my website, I pull the changes from Github. I execute webpack in the command line, and it seems to be working fine. Next, I run my expressHost.js file to host the site. However, when I try accessing the site, I encounter the error mention ...

Loading necessary CSS when needed in React JS

I am currently in the process of converting a bootstrap template to react framework. My question is, is there a way for me to load stylesheets on demand? For instance, if I have 2 components and I import the same stylesheet separately in both components, ...

Sequentially traverse the tree in reverse preorder fashion

My goal is to locate the element that is positioned directly above another element in the layout. This could mean the element is nested within several levels of the DOM structure, or it may involve moving up a few levels in the hierarchy. For instance: di ...

How to sync two carousels in Bootstrap 5 to slide simultaneously with just one click on the next and previous buttons

I am trying to implement dual sliding carousels using Bootstrap 5, but I am encountering issues with getting them to slide simultaneously. Despite incorporating data-bs-target=".carousel", the synchronization isn't working as intended in my ...

What is the process for capturing the entire REST API response in Vugen?

Having trouble obtaining the full JSON response in VUGEN. It's my first time scripting in VUGEN and I'm using the web-HTTP/HTML protocol. I've written a simple script to make a POST request to a REST service. Action() { web_rest("POST: htt ...

What is the best way to add data to a URL in an ActionResult Method using window.location.href?

I am having trouble understanding how to retrieve data using window.location.href = '/Product/Success/'+data.OrderTrackNo+'';. I am able to get data using ajax, but it seems different when retrieving data with window.location.href, whic ...

Utilizing Input Data from One Component in Another - Angular4

As a newcomer to Angular, I'm facing an issue where I need to access a variable from ComponentA in ComponentB. Here's the code snippet that demonstrates what I'm trying to achieve (I want to utilize the "favoriteSeason" input result in the " ...

Is there a way to retrieve the file path of the file that is imported using an alias in Vite (Vue3)?

Hello! I have a few inquiries. Is it feasible to obtain the file path of the file utilizing an alias for import in Vite (Vue3)? Setup Here's the directory structure I'm using, purely for illustrative purposes: src/ module_a/ some_ ...

Can you point me in the direction of the jQuery library link?

Can anyone assist me in locating the direct link to the jquery library for inclusion on my website? I have tried searching on the official website, but it doesn't seem to have the information I need or it's not clear enough. I only need the link ...

Exploring the full potential of MongoDB with Discord.js through a single entry point

I'm currently facing an issue with a command that checks someone else's balance within my economy system. The problem is that it only stores one user's data at a time. So, when the database is empty and the bot tries to create a profile for ...