DEV Community

Discussion on: Debugging Challenge: The cursed default clause

Collapse
 
willsmart profile image
willsmart

Love it. That's really counterintuitive but makes sense.

As a carry over from working in c and c++ I've always enclosed any case blocks that define variables in curlies, since it avoids redeclaring variables if you have two cases declaring under one name (a similar issue to this one).
So, my code would be:

function handleError(error) {
  switch (error) {
    case 404:
      console.log("Document not found");
      break;

    case 500:
      console.log("Server Error");
      break;

    default:
      {
        const error = {
          msg: "Got an unknown error code",
          timestamp: Date.now()
        };
        console.log("Unknown Error Incident", error);
      }
      break;
  }
}

handleError(404); // should log "Document not found", now it does