Skip to content
← Back to Snippets
Code

Basic Exception Handling (try-catch)

Uses try-catch around a risky operation and returns either the parsed value or a safe public error message.

Purpose

Uses try-catch around a risky operation and returns either the parsed value or a safe public error message.

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.
 */

/**
 * Basic Exception Handling (try-catch).
 *
 * Purpose:
 * Parses JSON inside try-catch and returns a safe result.
 *
 * @param string $json_text JSON text to parse.
 * @return array Parse result.
 */
function ogSnippetBasicExceptionHandling(string $json_text): array {
	$result = array(
		'ok' => false,
		'data' => array(),
		'message' => 'JSON could not be parsed.'
	);

	try {
		$data = json_decode($json_text, true, 512, JSON_THROW_ON_ERROR);

		if (is_array($data) === true) {
			$result['ok'] = true;
			$result['data'] = $data;
			$result['message'] = 'JSON parsed successfully.';
		}
	} catch (JsonException $exception) {
		$result['message'] = 'JSON could not be parsed.';
	}

	return $result;
}

$parse_report = ogSnippetBasicExceptionHandling('{"ship":"Serenity","status":"flying"}');

echo 'Try-catch result: '.$parse_report['message'];