From 3841574435fe7c585d0551b87c0850812a5ca041 Mon Sep 17 00:00:00 2001 From: Mark Doliner Date: Mon, 1 Jun 2020 11:14:45 -0400 Subject: [PATCH] Add a StructLike class that extends Error. Exception classes should extend this so that they derive from Error. As mentioned in [the GitHub issue](https://github.com/creditkarma/thrift-typescript/issues/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. --- packages/thrift-server-core/src/main/types.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/thrift-server-core/src/main/types.ts b/packages/thrift-server-core/src/main/types.ts index e10aa291..b2efb530 100644 --- a/packages/thrift-server-core/src/main/types.ts +++ b/packages/thrift-server-core/src/main/types.ts @@ -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 { new (args?: any): T read(input: TProtocol): T