Help Your Fellow Developers with Well-Worded Error Messages

When something goes wrong in my code, I usually try to throw an error with a message telling me what went wrong. I don’t think too much about what the error message is. It’s usually just enough to give me an idea about why the code raised an exception.

Recently, one of my co-workers pointed out an improvement I could make: Write error messages that won’t make him think. A good error message should not only point out a problem in your code. It should also indicate that a solution is available.

My Typical Error Messages

This topic came up after my co-worker had to make changes to a script that I made that automatically entered a team’s project hours into a spreadsheet. Before the script would start writing numbers on a spreadsheet, it would check for a header in a specified row. If it didn’t find the header, it would raise an exception like this:

Screenshot of error message that reads: RuntimeError: Headers don't match - ACTUAL !=Expected

(ACTUAL and EXPECTED were the mismatching columns in the header.)

To me, it was obvious that this error message meant the header must have been moved, and the fix was simple. I needed to update the headerRowLocation variable to the correct row number.

However, this message was not so helpful to people who hadn’t developed the script. It provided a starting point to read through my script, but it didn’t point out the actual issue.

A Helpful Error Message

My error message simply said what happened in my code. Instead, it should have given the developer context about the problem and a potential solution. A better error message should say something like this:

Screenshot of error message that says "RuntimeError: Headers do not match. Check to see where the header is located on the spreadsheet and change the 'headerrowlocation' variable to be the correct row.

This message doesn’t just indicate that there is a problem. It helps solve the problem. With a message like this, developers don’t have to spend extra time and effort reading through someone else’s code, and they can move on to more important things.

The Benefits of Better Wording

Once I started trying to write error messages that include solutions, I immediately noticed a few benefits:

  • Developers who have to work on your code don’t have to waste time solving problems you already thought about.
  • I write more error messages, which forces to me look for potential problems in my code.
  • These sorts of messages provide more documentation on how the code should behave.

Go Slow to Go Fast

Next time you’re coding something that will raise an exception, try taking a step back to figure out why the code is breaking. Take the time to write an error message that allows fellow developers to correct the problem quickly and efficiently, allowing them to focus their attention on other issues they are facing.

  • Tom Corwine says:

    Error: Something went wrong.

  • Comments are closed.