phpMick's avatar
Level 15

Custom exceptions.

When do I nee d to use custom exceptions?

I am printing labels (in a class) and I want to throw an exception back to the controller if the image is missing.

if($item->drawing->bmp==null){
                throw new Exception("Image not uploaded for shape $shape");
            }

Is this OK, or should I be using a custom exception?

Mick

Mick

0 likes
4 replies
ohffs's avatar

Custom exceptions are handy if you want to trap them specifically outside of a generic exception that can be caused by something else. For instance if you have a custom exception of InvalidImageDimensions then you could use it like :

...
try {
    $resizedImage = $this->resizeImage($originalImage, 1024, -768);
} catch (InvalidImageDimensions $e) {
    // do something specific
} catch (Exception $e) {
    // some other thing
}

Maybe you only want to catch your own exceptions and let the others bubble up the system etc. In general I think they're best used sparingly though.

martinbean's avatar

@phpMick Completely up to you, but custom exception classes are a bit easier to diagnose than a generic Exception with a message.

Consider:

throw new \App\Labels\ImageMissingException;

Over:

throw new \Exception('Image is missing.');

Looking at the former in your logs, you’d be able to instantly see what the issue is from the exception class’s name.

phpMick's avatar
Level 15

I think I got it.

I will do it like this:

}catch(\LabelPrintingException $            

"Turn the printer on you muppet"

        }catch(\Exception $e){
   
    Log the actual error.
    Nice message to user.
        }

The I can handle them differently, with LabelPrintingException I can pass a message to the user, if any other exception happens, i can just log it.

Mick

Please or to participate in this conversation.