Cannot read properties of undefined (reading 'push') when calling `segment.close(error)`
- Dominant language
- JavaScript
- Stars
- 280
- Forks
- 157
- PR merge metrics
- No merged PRs in 30d
Description
**Error trace**
```
Cannot read properties of undefined (reading 'push')","stack":["TypeError: Cannot read properties of undefined (reading 'push')"," at Segment.addError (/app/node_modules/aws-xray-sdk-core/dist/lib/segments/segment.js:253:27)"," at Segment.close (/app/node_modules/aws-xray-sdk-core/dist/lib/segments/segment.js:316:14)
```
**Steps to reproduce**
I got this error under the specific scenario:
1. Create a segment, create a subsegment inside that parent segment.
2. Call `subsegment.addError(err)` with an error.
3. Afterwards in the main parent segment, call `segment.close(err)` with the same error.
4. Library throws the error specified above.
**Code snippet**
On `/packages/core/lib/segments/segment.js`
```
Segment.prototype.addError = function addError(err, remote) {
if (err == null || typeof err !== 'object' && typeof (err) !== 'string') {
logger.getLogger().error('Failed to add error:' + err + ' to subsegment "' + this.name +
'". Not an object or string literal.');
return;
}
this.addFaultFlag();
if (this.exception) {
if (err === this.exception.ex) {
this.cause = { id: this.exception.cause };
delete this.exception;
return;
}
delete this.exception;
}
if (this.cause === undefined) {
this.cause = {
working_directory: process.cwd(),
exceptions: []
};
}
this.cause.exceptions.push(new CapturedException(err, remote));
};
```
I think the error here is because [the subsegment is setting](https://github.com/aws/aws-xray-sdk-node/blob/master/packages/core/lib/segments/attributes/subsegment.js#L228) its parent `exception` when `subsegment.addError` is called.
Then when trying to close the parent segment with the same error, it overwrites the cause with a new cause object that do not contain the `exceptions` array. So on line 311 of `/packages/core/lib/segments/segment.js` the call to push fails, because there's no array.
I think this can be fixed in the same way the other issue was resolved.
```
this.cause = {
id: this.exception.cause,
exceptions: [] // Also initialize the array to prevent error on `this.exceptions.push(...)`
};
```
**Related issues**
I found a somewhat similar issue, that affected the `subsegment.addError` logic, created some time ago:
* https://github.com/aws/aws-xray-sdk-node/issues/448
Contributor guide
Assessment
This issue has not been assessed yet.