Techniques for returning errors to the calling function using async functions

I am currently encountering an error where if "dateofBirth" is not found, an empty object is sent back to the client. How can I change this so that an error object is sent back instead of an empty object? Essentially, I want to send back a catch process.

main.ts

export class GetSpecialtyQuestionsController extends Controller {
        public static async process(@Request() request: ExpressRequest,
            response: ExpressResponse): Promise < any > {
            try {
                const instance = new GetSpecialtyQuestionsController();
                const data = await instance.execute(request);
                response.status(200);
                response.send(data);
            } catch (err) {
                response.status(200);
                response.send(err.message);
            }

        }

        // private _request: IRequestURL[] = [];

        constructor() {
            super();
        }

        private async execute(@Request() request: ExpressRequest): Promise < any > {
            // const specialtyMembers = this.getSpecialtyMemberInfoFakeObject();
            const specialtyMembers = await new SpecialtyCacheUtility().getSpecialtyMemberInfoCache(
                request.body.getSpecialtyQuestionsRequest.header.serviceContext.tokenID);
            if (!specialtyMembers) {
                return this.errorHandler(request);
            }
            let proxyMember: ISpecialtyInfoObj = {}
            as ISpecialtyInfoObj;
            for (const member of specialtyMembers) {
                if (member.specialtyIdEnc === request.body.getSpecialtyQuestionsRequest.details.specialtyIdEnc) {
                    proxyMember = member;
                    if (!member.dateOfBirth) {
                        throw new Error('no patient info for given HBS ID');
                    }
                    break;
                }
            }

        }

Answer №1

Implementing a custom exception object for passing data when throwing an error

class CustomError extends Error {
  constructor(bar = 'foo', ...params) {
    // Forward remaining arguments to parent constructor
    super(...params);

    // Preserve stack trace information (V8 only)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    // Additional debug details
    this.bar = bar;
    this.timestamp = new Date();
  }
}

try {
  throw new CustomError('foobar', 'error message');
} catch(err){
  console.log(err.bar); // foobar
  console.log(err.message); // error message
  console.log(err.stack); // stacktrace
}

For more information, refer to the official MDN documentation - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

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

Combining data from various API calls into one cohesive array using RXJS

My RXJS Pipeline is structured as follows: const logs: number[] = [1, 2, 3, 4]; const url = 'http://some-url-here.com'; const pipeline = from(logs).pipe( switchMap(logId => this.callEndpoint(url, logId).pipe(map(response => response. ...

The error message "node-soap - callback is not a function" is indicating that there

Encountering a common TypeScript error while calling a SOAP method on a node-soap client in NodeJS. Seeking guidance on resolving this issue. https://www.npmjs.com/package/soap - version: 0.35.0 Sample Code Snippet const [result] = await mySoapClient.Per ...

Is there a way I can utilize canvas to overlay one image onto another?

Is there a way to merge one image into another by using a transparent box? It's not just about copying and pasting an image into another. I also want to know how to transform the image to fit perfectly within the other image. For example, similar to ...

What is the best way to retrieve the value of a property within a JavaScript object?

I am facing an issue with retrieving the value of the status property from an object in my code. Below is a snippet of what I have tried: console.log("Resource.query()"); console.log(Resource.query()); console.log("Resource.query().status"); console.log(R ...

Utilizing React and Material-UI to create an autocomplete feature for words within sentences that are not the first word

Looking to enable hashtag autocomplete on my webapp, where typing #h would display a menu with options like #hello, #hope, etc. Since I'm using material-ui extensively within the app, it would be convenient to utilize the autocomplete component for th ...

The return type from the RxJS Observable reduce method may differ from the type initially provided

Dealing with Angular4, TypeScript, and RxJS 5 I am encountering an issue where I have a complex type being passed into a reduce method, but I want the return type to be a simple boolean value. Currently, the following code is giving me a return type erro ...

The initialization process of Vue.js router is compatible with router.map, but not with the Router constructor

I'm experiencing an issue in my app where routes work fine when I use router.map({}) with the vue-router, but they fail to work when I pass them directly in the constructor. Any insight into why this might be happening? // Routes that work: const rou ...

Mastering Array Dispatch in VueJS

I've encountered an issue while trying to send an array of data to the backend. I attempted to include [] in the dispatch variables and on the backend, but it only captures the last data sent to the backend. My objective is to associate each data with ...

Ways to retrieve the text of the chosen radio button label with the help of jQuery

There is a radio button on my webpage that looks like this: <div id="someId"> <label class="radio-inline"> <input name="x" type="radio" onchange="GetSelectedVal();">Yes</label> <label class="radio-inline"> ...

Passing data between pages in Node.js

My current project involves creating a web service using node.js. In this setup, I am utilizing curl to send POST data to my index.js application. The index.js app processes the received data and I need it to then route the output to various pages based on ...

The ng command seems to be malfunctioning when executed from a separate directory

After selecting a different folder for my new angular project, I encountered an error every time I tried to run an ng command: 'ng' is not recognized as an internal or external command, operable program or batch file. I attempted to resolve ...

Create an HTML and CSS code that allows you to split paragraph text into columns within a

I am seeking a way to create dynamic paragraph column text using only the https://i.sstatic.net/ZX1AN.png Here is an example of how it could be displayed in HTML: <div> <p> Sed ut perspiciatis, unde omnis iste natus error sit voluptatem ...

Resource file for locating the mappings

As a beginner in sourcemapping, I have been tasked with saving the sourcemap in an external file. However, up to this point, I have only been able to concatenate the sourcemap to the minified .js file. What changes should I make to my approach? Am I miss ...

Placing a div over a JavaScript element

Is it feasible to overlay a div(1) with a background image on top of another div(2) that contains JavaScript (like Google maps API v3)? I have experimented with z-index without success, and I am unable to utilize absolute positioning because I depend on t ...

"The Vue.js/JavaScript object updates, but the changes are not being displayed in the document object model (DOM

Currently, I am endeavoring to iterate through an array of objects and display them as list items. There is a click listener that introduces a custom property to the object, and a class binding depends on the value of that property. Would you mind reviewin ...

Code running successfully in Chrome's console, but encountering issues when executed on the webpage

Having some trouble assigning a function to a button in JavaScript. This is the button I'm working with, and my main goal right now is to make it responsive. <button id="artbtn" class="artbtn btn">Art</button> I experimented with this in ...

Error: An unexpected token '<' was encountered during the React Webpack build process

My ReactJs project is using Webpack4 and @babel/core 7. However, when I attempt to build the project, I encounter the following error in the terminal: ERROR in ./src/views/Pages/Login/Login.js Module build failed (from ./node_modules/babel-loader/lib ...

Retrieve the number of rows in the table component

I'm in need of getting the row count from a table component that I have built using vuejs. My goal is to display the row count outside of the table component structure. The issue with the code snippet below is that it doesn't show the correct row ...

Node.js refuses to launch - the dreaded error 404, signaling that it has mysteriously vanished

I am brand new to node.js, so please be patient with me as I learn. Currently, I am using the express framework and attempting to create a basic application that displays content as HTML. Below is the essentials of my app.js: var express = require(' ...

What is the best way to populate nested elements with jQuery?

I am trying to showcase the latest NEWS headlines on my website by populating them using Jquery. Despite writing the necessary code, I am facing an issue where nothing appears on the webpage. Below is the HTML code snippet: <div class="col-md-4"> ...