DEV Community

Cover image for Debugging Challenge: The cursed default clause

Debugging Challenge: The cursed default clause

Sebastian Stamm on September 02, 2019

An evil witch cursed my switch statement so that no matter what I put in, it always executed the default clause instead of the case clauses. This ...
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
Collapse
 
brunooliveira profile image
Bruno Oliveira

Damn, awesome job!! I mean, not as a JS expert, but, as a fellow programmer, I can only imagine the joy when finding this out!!