Skip to content

Commit

Permalink
Add a StructLike class that extends Error.
Browse files Browse the repository at this point in the history
Exception classes should extend this so that they derive from Error.

As mentioned in [the GitHub issue](creditkarma/thrift-typescript#178), this is useful because it causes Thrift exceptions to have stack traces and because some frameworks expect exceptions to derive from Error. The GitHub issue mentions graphql-js. Jest's `toThrow()` function would also benefit from this. Here's an example:

```
await expect(thriftClient.someFunction()).rejects.toThrow()
```

`toThrow` doesn't identify Thrift exceptions as exceptions because they don't derive from Error and so it will return false in such cases. Part of the blame could fall on Jest, because perhaps `toThrow` should return true for any rejected promise regardless of the type of object being throw, but I think some of the blame still falls on Thrift.

Possible remaining work:
- Add a test?
- Bump version number so end users can require the new version.
  • Loading branch information
markdoliner-doma committed Jun 1, 2020
1 parent 5787abd commit 3841574
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/thrift-server-core/src/main/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,22 @@ export abstract class StructLike implements IStructLike {
public abstract write(output: TProtocol): void
}

/**
* Like `StructLike` but extends `Error`. Exception classes extend this.
*/
export abstract class ErrorStructLike extends Error implements IStructLike {
public readonly name: string
public readonly _annotations: IThriftAnnotations = {}
public readonly _fieldAnnotations: IFieldAnnotations = {}

constructor() {
super()
this.name = this.constructor.name
}

public abstract write(output: TProtocol): void
}

export interface IStructConstructor<T extends StructLike> {
new (args?: any): T
read(input: TProtocol): T
Expand Down

0 comments on commit 3841574

Please sign in to comment.