Finding Bugs using a Binary Search

Finding bugs in your code when the error message is not helpful or there is no error message


In the previous article, we looked at an odd case of resources that save with no errors but don't show up in the Resource tree. In this one we'll look at a way to find bugs in your code using a binary search.


MODX logo

The Problem

Sometimes, your code will produce a not-very-helpful error message like this one:

    PHP notice: Undefined offset: 2
    

Sometimes, you'll get a line number that points to the error, but sometimes you won't. At other times, the error message will give you an idea that helps you find the problem, but sometimes it's a complete mystery. For those cases a binary search can help you find the problem.


The Solution

Add this line about half-way through your code:

$modx->log(modX::LOG_LEVEL_INFO, 'Made it to here');

If the "Made it to here" message shows up before the error message, the error is in the second half of your code. If not, it's in the first half.

Once you've determined which half of the code contains the error, move the "Made it to here" log line to the middle of that section and run the code again. That will tell you which half of that section the error is in.

Keep on splitting the code with the "Made it to here" message until you've located the specific line of code that's causing the error.


What if the Code just Crashes with no Error Message?

You can still use a binary search to locate the problem. Put the "Made it to here" line in the middle of the code. If the error message appears in the log, the problem is in the second half of the code. If not, it's in the first half.

Keep splitting the difference until you find the problem.

I should mention that with plugins and CMPs, a syntax error in your code can lead to a crash with no error message and nothing in the log. The best solution to this is a good code editor like PhpStorm that will catch your errors as you write the code. See this article for another method.


Coming Up

In the next article, we'll see how to keep the MODX forums from eating your back-ticks.



For more information on how to use MODX to create a web site, see my web site Bob's Guides, or better yet, buy my book: MODX: The Official Guide.

Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)



Comments (0)


Please login to comment.

  (Login)