Nick Audenaerde
Nick Audenaerde

Reputation: 1025

User friendly php try catch

Since a short period of time I'm working with Try Catch in PHP. Now, every time a new error is thrown you get a fatal error on the screen, this isn't really user friendly so I was wondering if there's a way to give the user a nice message like an echo instead of a fatal error.

This is the code I have now:

public static function forceNumber($int){
    if(is_numeric($int)){
        return $int;
} else {
        throw new TypeEnforcerException($int.' must be a number');
}
}

public function setStatus($status) {
    try {
        $this->status = TypeEnforcer::forceInt($status); 
    } catch (TypeEnforcerException $e) {
        throw new Exception($e->getMessage());
    } catch (Exception $e) {
        throw new Exception($e->getMessage());
    }

}

Upvotes: 1

Views: 7701

Answers (1)

hakre
hakre

Reputation: 197624

This is best solved with a frontend controller that is able to catch all uncatched exceptions:

<?php
require('bootstrap.php');

try {
    $controllerService->execute($request);
} catch (Exception $e) {
    $controllerService->handleControllerException($e);
}

You can then write code to return the internal server error because an exception signals an exceptional case so it normally is an 500 internal server error. The user must not be interested what went wrong other than it just didn't work out and your program crashed.

If you throw exceptions to give validation notices you need to catch those in a different layer (and you're probably doing it wrong if you use exceptions for that).


Edit: For low-level functions, because PHP is loosely typed, if a function expects and int, cast to intDocs:

public static function forceNumber($int){
    $int = (int) $int;
    return $int;
}

this will actually force the integer. In case the cast is not possible to do (e.g. $int it totally incompatible) PHP will throw the exception for you.

The example is a bit akward because by the method's name you use it to validate some number and provide an error if not (here wrongly with an exception). Instead you should do some validation. If you expect wrong input, it's not an exceptional case when wrong input is provided, so I would not use exceptions for that.

Upvotes: 5

Related Questions