Reputation: 5235
I'm using a throwExecption
when a file is not specified in request and at the end of my fonction I use finally
block to unlink file.
So I case file
is not specified I should get 400 code with error message.
But because of finally
block throw Execption
is getting overrided by it
try {
if (!file) {
throw new BadRequestException('no file');
}
}
...
finally {
// On error or not : delete temporary file
await fse.unlink(file.path); // error 500 because Cannot read property 'path' of undefined
}
I have found a workaround if to check file in finally
block , but that makes code redundant.
try {
if (!file) {
throw new BadRequestException('no file');
}
}
...
finally {
// On error or not : delete temporary file
if (file) {
await fse.unlink(file.path);
} else {
throw new BadRequestException('no file'); <== redundancy
}
}
Is there another way to handle this case of error ?
Upvotes: 1
Views: 315
Reputation: 8183
You can move the if block outside of try/catch block
if (!file) {
try {
...your block of code
}
...
finally {
// On error or not : delete temporary file
await fse.unlink(file.path);
}
} else {
throw new BadRequestException('no file'); <= = redundancy
}
Upvotes: 2