PHP Exception Handling - ErrorException

PHP Exception Handling – LengthException

Making our way through our in-depth PHP Exception Handling series, on this fine day we’ll be going over the LengthException in PHP. LengthException is not a complex beast by any stretch of the imagination. Instead, it’s merely meant to be thrown when a value length should be considered invalid.

Throughout this article we’ll explore the LengthException in more detail, by starting with a look at where it sits in the PHP Exception Hierarchy. We’ll also examine some functional sample code that will illustrate how LengthExceptions should be used in your own code, so away we go!

The Technical Rundown

Full Code Sample

Below is the full code sample we’ll be using in this article. Feel free to use any or all of the code if you wish to follow along.

When Should You Use It?

Most modern applications these days use some kind of data layer to retain permanent records, whether this be user credentials (not recommended) to cute puppy pictures (highly recommended). If your application accepts user or third-party data in some way, it’s paramount that the code provides sanity checks and data validations. These can be as complex as your business logic demands, but the most basic data validation, which should be applied before it is sent to the database, is checking the length of data. Hence, this is where the use of the LengthException can come in quite handy when writing PHP applications.

For our example code today, we’ll be extending my favorite Book example class, which contains a few simple properties: author, title, and pageCount. For the sake of this tutorial, we’ve decided our database columns only need to handle a maximum of 255 bytes for the author value and 65,535 bytes for the title. Maybe the CTO did some research and looked into the commonality of names and/or book titles exceeding those lengths, and decided those were smart limits. Please play along for the sake of the example, since most modern applications would obviously not impose such strict limitations without extremely good reason.

Anyway, to accomplish such restrictions we’ve added some basic length validation logic to our Book->setAuthor(string $author) and Book->setTitle(string $title) methods:

We’ve also defined our aforementioned maximum byte lengths as const values, to keep the code a bit cleaner. As you can see, in the event that the strlen(string $string) function returns a value that exceeds the defined maximum length, a new LengthException is thrown with a message indicating the problem.

In order to create multiple Book instances with varying title and author lengths, we’ve created a simple createBookTest(string $title, string $author, int $pageCount) function. By creating a separate function with its own locally scoped try-catch block, we can safely catch any thrown exceptions without halting execution of the other Book creation calls. This function simply passes along its parameters to the Book constructor and attempts to output the created book instance to the log:

Alright, now everything is setup, so let’s test it out! We start with a basic book, just to confirm everything works normally, as expected:

Sure enough, everything looks good in the log output:

Now, let’s try creating some books using our maximum length values for title and author, then also attempt a book creation that exceeds the maximum length of each of those by one:

As you probably guessed, the attempts to create books with title and author values equal to the maximum worked fine, while those calls that exceeded the maximum threw LengthExceptions with our custom error message, as intended:

Let’s try one last thing and throw in a less-common character into our repeated author argument value:

Here we’re using the kanji character, which commonly means “person.” Even though we are creating an author value of Book::AUTHOR_MAX_LENGTH length — just as we did before — now we’re seeing another LengthException:

So what’s going on? The important lesson here is that the strlen(string $string) function, which we’re using to test various lengths, doesn’t explicitly return the character count. Instead, it returns the number of bytes that make up that string. For the common alphanumeric characters most Westerners use everyday, such as those belonging to the Roman alphabet, the character count and the byte count are one in the same. However, more complex characters require additional bytes to store their data.

As it happens, if you are keen with numbers, you may have determined that the number of bytes used by our kanji example (765) is exactly three times the maximum number of 255. We can then deduce that each kanji character requires 3 bytes to store.

Now we can modify our example by dividing the length of our string by 3, which will ensure the number of bytes required by our created author string is equal to the Book::AUTHOR_MAX_LENGTH:

Sure enough, this works just fine and creates a new Book instance in the output:

Check out the Airbrake-PHP library, designed to quickly and easily integrate into any PHP project, giving you and your team access to real-time error monitoring and reporting throughout your application’s entire life cycle. With automatic, instantaneous error and exception notifications at your fingertips, you’ll be constantly aware of your application’s health, including any issues that may arise. Best of all, with Airbrake’s robust web dashboard cataloging every error that occurs, you and your team can immediately dive into the exact details of what went wrong, making it easy to quickly recognize and resolve problems.