Reputation: 8993
I am using async/await a lot these days but I have a mocha test in which I am testing to ensure that an error is indeed thrown. Below you can see the try/catch block I have to capture this error. The green and grey squares are inserted by Wallaby (a real-time testing tool) and indicate that the catch block is never reached.
When I run mocha from the command line I get the following message:
UnhandledPromiseRejectionWarning: FireModel::WrongRelationshipType: Can not use property "employer" on fancyperson with addToRelationship() because it is not a hasMany relationship [ relType: ownedBy, inverse: undefined ]. If you are working with a ownedBy relationship then you should instead use setRelationship() and clearRelationship().
the first line of the addToRelationship()
checks to see if the relationship type is correct (it is not) and throws the error:
The _errorIfNotHasManyReln
method is rather unexciting but for completeness, here it is:
protected _errorIfNotHasManyReln(
property: Extract<keyof T, string>,
fn: string
) {
if (this.META.property(property).relType !== "hasMany") {
const e = new Error(
`Can not use property "${property}" on ${
this.modelName
} with ${fn}() because it is not a hasMany relationship [ relType: ${
this.META.property(property).relType
}, inverse: ${
this.META.property(property).inverse
} ]. If you are working with a ownedBy relationship then you should instead use setRelationship() and clearRelationship().`
);
e.name = "FireModel::WrongRelationshipType";
throw e;
}
Can someone help me identify why this error isn't being trapped? In desperation I added another try/catch block around the calling of call to _errorIfNotHasManyreln
and it DOES catch the error but then I try and re-throw it and end up in the same situation again.
Upvotes: 2
Views: 204
Reputation: 1976
Your addToRelationship method is also async. You have to await
the promise response as well :
try {
await bob.addToRelationship("employer", "4567");
}
catch(e) {
[...]
}
If not delayed until the promise rejects then the try/catch didn't receive anything synced and terminated. Then the exception occurs which was obviously not caught.
Upvotes: 2