Bubbling return values in PHP

I got this crazy idea few years ago while building a REST service for one of my projects. I needed some way to represent complex errors happening deep down in the components of the service to the public.

I ended up returning arrays with multiple keys which was really not ideal.

Imagine a simple situation, a request to delete a resource:

In return scenario you would get TRUE when the resource was deleted successfully and FALSE when something prevented delete action to happen. That leaves you uninformed which you can’t really act upon, because you don’t know how.

I think return should be used only when processing some value and the return is expected. What isn’t expected are exceptions.

I suddenly realised I got the solution under my nose all time.

Exceptions to return complex results

Exceptions could handle errors and return values of the precious example like:

  1. validation of the request failed;
  2. resource does not exists, so there’s nothing to delete;
  3. successful deletion of resource;
  4. access not allowed

and these are just few I could come out in this very moment.

If you are interested to try out this concept, I’ve open-sourced the modified Exception class with HTTP status codes support.

Usage is simple. In the beginning of the file declare use of class:

<?php

use \attitude\Exception\Exception;

Use trycatch sequence:


function deleteFile($file)
{
    if (!unlink($file)) {
        throw new Exception(500, "Failed to unlink {$file}");
    }

    throw new Exception(204); // No content header, means deletes successfully
}

try {
    deleteFile('/path/to/file/to/delete/example.txt');
} catch(Exception $e) {
    // Dispatch passed HTTP header, 500 or 204 in this case
    $e->header();

    // Print info to the output
    echo $e->getMessage();
}

I'm curious to hear your thoughts on this in the comments below.

Enjoy!