Skip to content
← Back to Snippets
Code

Custom Exception Class

Defines a focused custom exception class with a safe public message and catches it without leaking internal details.

Purpose

Defines a focused custom exception class with a safe public message and catches it without leaking internal details.

Snippet details

ContextError HandlingLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Custom exception for a mission rule failure.
 */
class OgSnippetMissionException extends RuntimeException {
	protected string $public_message = '';

	/**
	 * @param string $message Internal exception message.
	 * @param string $public_message Safe public message.
	 */
	public function __construct(string $message, string $public_message) {
		$this->public_message = $public_message;
		parent::__construct($message);
	}

	/**
	 * @return string Safe public message.
	 */
	public function getPublicMessage(): string {
		return $this->public_message;
	}
}

/**
 * Custom Exception Class.
 *
 * Purpose:
 * Throws and catches a focused exception with a safe public message.
 *
 * @param int $crew_count Number of available crew members.
 * @return array Mission check result.
 */
function ogSnippetCustomExceptionClass(int $crew_count): array {
	$result = array(
		'ok' => false,
		'message' => 'Mission check failed.'
	);

	try {
		if ($crew_count < 1) {
			throw new OgSnippetMissionException('No crew available for mission.', 'Mission cannot launch without crew.');
		}

		$result['ok'] = true;
		$result['message'] = 'Mission can launch.';
	} catch (OgSnippetMissionException $exception) {
		$result['message'] = $exception->getPublicMessage();
	}

	return $result;
}

$mission_check = ogSnippetCustomExceptionClass(4);

echo 'Custom exception result: '.$mission_check['message'];