creditkarma / thrift-typescript

Generate TypeScript from Thrift IDL files
Apache License 2.0
155 stars 32 forks source link

Add server-side logging of non-Thrift exceptions. #186

Open markdoliner-doma opened 4 years ago

markdoliner-doma commented 4 years ago

BACKGROUND

Two kinds of exceptions can be thrown by a handler processing a Thrift request:

THIS CHANGE

I modifed the code that generates the server processor to include a console.error() statement that logs exception messages and stack traces when a handler throws a non-Thrift exception. Previously there was no server-side logging for non-Thrift exceptions. The message was sent to the client and the stack trace was discarded entirely. This is not sufficient. Even if you have the exception message received by the client that may not be enough to determine where the error happened. And if you don't control the client then you're REALLY out of luck.

There are no other calls to console.log() or console.error() in the generated code. It could be argued that it's bad form for the generated code to use console.error() since it's sort of like a library, but I think it's more important to log the exception. A better solution might be to allow server implementors to provide a callback function for logging, but I leave that as an exercise for a future developer.

I updated both the Apache code and the thrift-server code, and the tests for both.

Here's the diff of a ping function generated for thrift-server before and after this change:

--- before  2020-07-27 08:05:20.000000000 -0400
+++ after   2020-07-27 08:05:13.000000000 -0400
@@ -1,23 +1,24 @@
     public process_ping(requestId: number, input: thrift.TProtocol, output: thrift.TProtocol, context: Context): Promise<Buffer> {
         return new Promise<string>((resolve, reject): void => {
             try {
                 input.readMessageEnd();
                 resolve(this._handler.ping(context));
             }
             catch (err) {
                 reject(err);
             }
         }).then((data: string): Buffer => {
             const result: IPing__ResultArgs = { success: data };
             output.writeMessageBegin("ping", thrift.MessageType.REPLY, requestId);
             Ping__ResultCodec.encode(result, output);
             output.writeMessageEnd();
             return output.flush();
         }).catch((err: Error): Buffer => {
+            console.error("Unexpected exception while handling ping:", err);
             const result: thrift.TApplicationException = new thrift.TApplicationException(thrift.TApplicationExceptionType.UNKNOWN, err.message);
             output.writeMessageBegin("ping", thrift.MessageType.EXCEPTION, requestId);
             thrift.TApplicationExceptionCodec.encode(result, output);
             output.writeMessageEnd();
             return output.flush();
         });
     }