S
S
Sashqa2020-03-26 17:05:23
Node.js
Sashqa, 2020-03-26 17:05:23

Error forwarding up node js?

I have the main file and in it In the router I have
app.use('/', router);

import {NextFunction, Request, Response} from "express";
import {sendHttpRequest} from "../../../projects/server/http-request";
import router from "../../../projects/routes";

router.get('/', ( async (req: Request, res: Response, next: NextFunction) => {
    try {
        let contractId = req.query.contractId;
        const err = await sendHttpRequest(contractId, token);
        res.send(err).end();
    }
    catch (e) {
        next(e)
    }
}));


In sendHttp, I call two methods that make a request to the database
export const sendHttpRequest = async (id: string, token: string) => {
    try {
        await getProductId(id, token);
        return getContractData(id, token);
    }
    catch (e) {
        console.error(e.message)
    }
};


Requests look like this
async function getProductId(id, token) {
    try {
        const variables = {};
        const options = {};
        const req = await fetch(url, options);
        const res = await req.json();
        if (res.data.entityObject.Produkt) {
            idProduct = res.data.entityObject.Produkt.ID
        } else {
            // как прокинуть ошибку вверх?
        }
    }
    catch (e) {
        console.error(e.message)
    }
}


Actually now the question itself. What do I need to write to get the error message up in the router?
that is, if I pass a non-working id, d router, to the function, I want to receive a message about it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Inviz Custos, 2020-03-26
@Sashqa

export const sendHttpRequest = async (id: string, token: string) => {
    try {
        await getProductId(id, token);
        return getContractData(id, token);
    }
    catch (e) {
        console.error(e.message);
        throw e;
    }
};

async function getProductId(id, token) {
    try {
        const variables = {};
        const options = {};
        const req = await fetch(url, options);
        const res = await req.json();
        if (res.data.entityObject.Produkt) {
            idProduct = res.data.entityObject.Produkt.ID;
        } else {
            throw new Error('Some error ...');
            // Или же: return Promise.reject(new Error('Some error ...'));
        }
    }
    catch (e) {
        console.error(e.message);
        throw e;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question