Tag Archives: error

Do not be alarmed – Or do!

This morning I watched a video on Rusts Error-Handling that Larry Garfield posted on Mastodon.

The essence – at least to me – is that Exceptions throw one out of the normal flow of execution just like GOTO does. And we all know that GOTO is bad. SO how does Rust handle Errors, when Exceptions are bad and we always want to return a defined type?

Rust uses Result “enums” instead of a dedicated type that a function returns instead of throwing an exception or returning null. They contain either the expected return value or an Error.

I am not a mathematician. So I might be getting things wrong from a logical point of view. But as a developer I do have a slightly different view on the topic of Error and Exception handling.

Continue reading Do not be alarmed – Or do!

Valid Syntax errors: Part 1

It took me about an hour to spot a strange behaviour in my PHP skript:

Have a look at this code:

$foo = array ( 'a', 'b', 'c' );
foreach ( $foo as $bar );
    echo $bar . "\n";
// Expected Output:
// a
// b
// c
// Actual Output: 
// c

What happened?

Would I have used phpcs it would have been obvious. I used a semicolon instead of a bracket after the foreach statement.

So instead of calling the echo command with each iteration the foreach silently iterated through $foo and assigned $bar on each iteration. That left $bar with the last value of the array that gave the strange output.

I can not actually remember whether there had been closing brackets but I did not get an Error regarding that.

phpcs would have detected the missing brackets — if that would be observed by the used sniff.

More on phpcs later.

unserialize values

Last week I had the problem, that – due to a wrong database-entry – a serialized value got scrambled. And due to that (and some missconfiguration of the server) the application broke. Instead of a search result the user simply got an error message about not being able to unserialize the value due to an offset-error.

So how could I avoid the error (which actually is a notice) being thrown and besides that get to know whether unserializing worked or not?

The hack I finaly came up with is as follows:

  • suppress the notice in any way
  • check whether the returned value is a boolean false and the given string is ‘b:0;’ (which represents a boolean false in a serialized string).
  • If so, the unserialize() failed, so lets throw an InvalidArgumentException

And here it is:

public function my_unserialize ( $value )
{
    $unserialized = @unserialize ( $value );
    if ( false === $unserialized && 'b:0;' !== $value ) {
        $le = error_get_last ();
        throw new InvalidArgumentException ( $le['message'] );
    }
    return $unserialized;
}