I have a method in a class that is supposed to only throw error log messages and then another method in another function that will get this errors and console them (for now).
The problem is that it just throws the error in the console and not in an upper level...
This are the methods from file1.ts
:
private sendToApp2(App2Url: string, logObject: object) {
try
{
let uriOptions = {
host: this.hostname,
port: this.port,
path: '/App2',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Api-version': '1'
}
};
this.App2Call(uriOptions, JSON.stringify(logObject));
}
catch (err) {
throw err;
}
}
private App2Call(params: Object, data: string) {
return new Promise((resolve, reject) => {
try {
let req = http.request(params, (response) => {
response.on('data', (data) => {
resolve(data);
});
}).on('error', (err: Error) => {
reject(new Error(err.message));
});
req.write(data);
req.end();
}
catch (err) {
reject(new Error(err.message));
}
});
}
And in the second file, I do this logic to catch the error and console it:
GetErrors() {
try {
// initialize the class object
let getErrors = new FirstClass();
await getErrors.sendToApp2(this.App2Url, this.logObject);
}
catch (err) {
console.log(err);
}
}
It looks like a simple case of having forgotten to use async
on the definition of sendToApp2
. Since it's not async
, there are no errors thrown during sendToApp2
since it returns before the promise from App2Call
rejects.
Where you're using sendToApp2
you're using await
, which suggests you're expecting it to return a promise, so just add async
to the definition:
private async sendToApp2(App2Url: string, logObject: object) {
// ^^^^^
Then the try
/catch
can handle rejections as errors.
Side note: Right now, there's no point to the try
/catch
in sendToApp2
, since all it does is throw err
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With