Home > other >  How to handle exceptions and cleanup on resources?
How to handle exceptions and cleanup on resources?

Time:08-30

I have the following TypeScript:

let socket: WebSocket
try {
  socket = new WebSocket(path, options)
  // do some more stuff with socket
} catch (e) {
  socket.terminate()
  throw e
}

This a familiar pattern from Java.

But my IDE is complaining at socket.terminate(): TS2454: Variable 'socket' is used before being assigned.

The alternative just seems super clunky:

let socket: WebSocket | null = null
  try {
    socket = new WebSocket(path, options)
    // do some more stuff with socket
  } catch (e) {
    socket?.terminate()
    throw e
  }

Is there a better way?

CodePudding user response:

The "clunky" way is the correct way, although if you don't use the socket again after the try...catch and you only re-throw after closing the (potentially-open) socket as an idempotent cleanup task, then the catch block is useless and can be replaced with try...finally to accomplish the same:

TS Playground

let socket: WebSocket | null = null;

try {
  socket = new WebSocket(path, options);

  // TS now knows that `socket` is definitely an instance of `WebSocket` within this block:
  socket;
//^? let socket: WebSocket

  // do some more stuff with socket
}
finally {
  socket?.terminate();
}

CodePudding user response:

Your IDE is right to complain - what if an exception occurs while the WebSocket is being created? In that case, socket wouldn't be set to anything. Your alternative seems to me not that clunky, and it handles the case that there's an error. If you use this pattern a lot, you could do this:

type NullableWebSocket = WebSocket | null;
  • Related