[FIXED] How to handle exceptions and cleanup on resources?

Issue

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?

I made a subtle change… maybe it’s better:

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

Solution

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();
}

Answered By – jsejcksn

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published