refactor(social): type the deliberate publish exceptions so they keep a clean message

After the failure-email sanitization, any non-SocialPublishException is shown to
the user as a generic line. The deliberate, user-facing throws in the X,
Facebook, Threads, and LinkedIn (+Page) publishers were plain \Exceptions, so
they'd have been genericized too — losing actionable messages like 'Unsupported
media type for Facebook' or 'X posts require either text or media'.

Convert those throws to their platform's SocialPublishException with a vetted
userMessage + category, so the publish failure surfaces a specific, safe message
(and the catch-all's generic line is reserved for genuinely unexpected errors).

Left as plain \Exception on purpose: the download helpers in Bluesky and Mastodon
(caught internally, returned as null — they never reach the email), and the
shared content-length guard in HasSocialHttpClient (no per-platform exception in
the trait, message is path-free, and it's already validated upstream).
This commit is contained in:
Paulo Castellano 2026-06-28 20:16:16 -03:00
parent 08e64ae074
commit 5b26747dde
6 changed files with 110 additions and 27 deletions

View file

@ -6,6 +6,7 @@
use App\Enums\Media\Type as MediaType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\LinkedInPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\PostPlatform;
@ -160,13 +161,19 @@ private function publishDocument(?string $content, $media, string $title): array
$document = $media->first(fn ($item) => $item->isDocument());
if (! $document) {
throw new \Exception("No PDF document for {$this->label()} document post");
throw new LinkedInPublishException(
userMessage: "No PDF document was found for this {$this->label()} document post.",
category: ErrorCategory::MediaFormat,
);
}
$documentUrn = $this->uploadDocument($document);
if (! $documentUrn) {
throw new \Exception("{$this->label()} document upload failed");
throw new LinkedInPublishException(
userMessage: "{$this->label()} did not accept the document. Please try again.",
category: ErrorCategory::ServerError,
);
}
$payload = $this->basePayload($content);
@ -262,7 +269,10 @@ private function uploadImage($mediaItem): ?string
$imageUrn = data_get($initData, 'value.image');
if (! $uploadUrl || ! $imageUrn) {
throw new \Exception("{$this->label()} image upload init missing uploadUrl or image URN");
throw new LinkedInPublishException(
userMessage: "{$this->label()} did not accept the image upload. Please try again.",
category: ErrorCategory::ServerError,
);
}
$tempFile = tempnam(sys_get_temp_dir(), 'li_image_');
@ -337,7 +347,10 @@ private function doUploadVideo(string $tempFile, $mediaItem): ?string
$uploadToken = data_get($initData, 'value.uploadToken', '');
if (! $videoUrn || empty($uploadInstructions)) {
throw new \Exception("{$this->label()} video upload init missing video URN or upload instructions");
throw new LinkedInPublishException(
userMessage: "{$this->label()} did not accept the video upload. Please try again.",
category: ErrorCategory::ServerError,
);
}
$uploadedPartIds = [];
@ -414,7 +427,10 @@ private function uploadDocument($mediaItem): ?string
$documentUrn = data_get($initData, 'value.document');
if (! $uploadUrl || ! $documentUrn) {
throw new \Exception("{$this->label()} document upload init missing uploadUrl or document URN");
throw new LinkedInPublishException(
userMessage: "{$this->label()} did not accept the document upload. Please try again.",
category: ErrorCategory::ServerError,
);
}
// The Documents API is not chunked — upload the PDF in a single request.
@ -475,13 +491,19 @@ private function waitForProcessing(string $resource, string $assetUrn, string $l
}
if ($status === 'PROCESSING_FAILED') {
throw new \Exception("{$this->label()} {$label} processing failed");
throw new LinkedInPublishException(
userMessage: "{$this->label()} {$label} processing failed.",
category: ErrorCategory::ServerError,
);
}
sleep($this->processingPollSeconds());
}
throw new \Exception("{$this->label()} {$label} processing did not complete in time");
throw new LinkedInPublishException(
userMessage: "{$this->label()} {$label} processing did not complete in time.",
category: ErrorCategory::ServerError,
);
}
/**
@ -505,7 +527,10 @@ private function downloadToTempFile(string $url, string $tempFile): void
$response = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($url);
if ($response->failed()) {
throw new \Exception('Failed to download media: HTTP '.$response->status());
throw new LinkedInPublishException(
userMessage: "Could not fetch the media to upload to {$this->label()}. Please try again.",
category: ErrorCategory::ServerError,
);
}
}

View file

@ -55,7 +55,10 @@ public function publish(PostPlatform $postPlatform): array
ContentType::FacebookReel => $this->publishReel($pageId, $accessToken, $content, $media->first()),
ContentType::FacebookStory => $this->publishStory($pageId, $accessToken, $media->first()),
ContentType::FacebookPost => $this->publishPost($pageId, $accessToken, $content, $media, $aspectRatio),
default => throw new \Exception("Unsupported Facebook content type: {$contentType?->value}"),
default => throw new FacebookPublishException(
userMessage: "Unsupported Facebook content type: {$contentType?->value}",
category: ErrorCategory::MediaFormat,
),
};
}
@ -64,7 +67,10 @@ private function publishPost(string $pageId, string $accessToken, ?string $conte
// Text only post
if ($media->isEmpty()) {
if ($content === null || $content === '') {
throw new \Exception('Facebook text posts require content. Please add text to your post.');
throw new FacebookPublishException(
userMessage: 'Facebook text posts require content. Please add text to your post.',
category: ErrorCategory::MediaFormat,
);
}
return $this->publishTextPost($pageId, $accessToken, $content);
@ -87,7 +93,10 @@ private function publishPost(string $pageId, string $accessToken, ?string $conte
return $this->publishMultiImagePost($pageId, $accessToken, $content, $media, $aspectRatio);
}
throw new \Exception('Unsupported media type for Facebook');
throw new FacebookPublishException(
userMessage: 'Unsupported media type for Facebook',
category: ErrorCategory::MediaFormat,
);
}
private function publishTextPost(string $pageId, string $accessToken, string $content): array
@ -173,7 +182,10 @@ private function publishMultiImagePost(string $pageId, string $accessToken, ?str
}
if (empty($attachedMedia)) {
throw new \Exception('Failed to upload any images to Facebook');
throw new FacebookPublishException(
userMessage: 'Failed to upload any images to Facebook',
category: ErrorCategory::ServerError,
);
}
// Create the post with attached media
@ -360,7 +372,10 @@ private function publishStory(string $pageId, string $accessToken, $media): arra
$videoId = $response->json()['video_id'] ?? null;
if (! $videoId) {
throw new \Exception('Facebook story upload failed: no video ID returned');
throw new FacebookPublishException(
userMessage: 'Facebook did not accept the story video. Please try again.',
category: ErrorCategory::ServerError,
);
}
$transferResponse = $this->facebookHttp()->post("{$this->baseUrl}/{$videoId}", [

View file

@ -5,6 +5,8 @@
namespace App\Services\Social;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\LinkedInPublishException;
/**
* Publishes posts to a LinkedIn company page on behalf of an administering member.
@ -21,7 +23,10 @@ protected function authorUrn(): string
$organizationId = $this->account->meta['organization_id'] ?? null;
if (! $organizationId) {
throw new \Exception('LinkedIn Page organization ID not configured');
throw new LinkedInPublishException(
userMessage: 'LinkedIn Page organization ID not configured',
category: ErrorCategory::Permission,
);
}
return "urn:li:organization:{$organizationId}";

View file

@ -4,6 +4,7 @@
namespace App\Services\Social;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\ThreadsPublishException;
use App\Models\PostPlatform;
use App\Services\Social\Concerns\HasSocialHttpClient;
@ -41,7 +42,10 @@ public function publish(PostPlatform $postPlatform): array
// Text only post
if ($media->isEmpty()) {
if (empty($content)) {
throw new \Exception('Threads text posts require content. Please add text to your post.');
throw new ThreadsPublishException(
userMessage: 'Threads text posts require content. Please add text to your post.',
category: ErrorCategory::MediaFormat,
);
}
return $this->publishTextPost($userId, $accessToken, $content);
@ -83,7 +87,10 @@ private function publishTextPost(string $userId, string $accessToken, string $co
$containerId = $containerResponse->json()['id'] ?? null;
if (! $containerId) {
throw new \Exception('Threads text container creation failed: no container ID returned');
throw new ThreadsPublishException(
userMessage: 'Threads did not accept the post. Please try again.',
category: ErrorCategory::ServerError,
);
}
// Step 2: Publish
@ -111,7 +118,10 @@ private function publishImagePost(string $userId, string $accessToken, ?string $
$containerId = $containerResponse->json()['id'] ?? null;
if (! $containerId) {
throw new \Exception('Threads image container creation failed: no container ID returned');
throw new ThreadsPublishException(
userMessage: 'Threads did not accept the image. Please try again.',
category: ErrorCategory::ServerError,
);
}
// Step 2: Wait for image processing
@ -142,7 +152,10 @@ private function publishVideoPost(string $userId, string $accessToken, ?string $
$containerId = $containerResponse->json()['id'] ?? null;
if (! $containerId) {
throw new \Exception('Threads video container creation failed: no container ID returned');
throw new ThreadsPublishException(
userMessage: 'Threads did not accept the video. Please try again.',
category: ErrorCategory::ServerError,
);
}
// Wait for video processing
@ -198,7 +211,10 @@ private function publishCarousel(string $userId, string $accessToken, ?string $c
}
if (empty($childContainers)) {
throw new \Exception('Failed to create any carousel items');
throw new ThreadsPublishException(
userMessage: 'Failed to create any carousel items',
category: ErrorCategory::ServerError,
);
}
// Step 2: Create carousel container
@ -219,7 +235,10 @@ private function publishCarousel(string $userId, string $accessToken, ?string $c
$carouselId = $carouselResponse->json()['id'] ?? null;
if (! $carouselId) {
throw new \Exception('Threads carousel container creation failed: no container ID returned');
throw new ThreadsPublishException(
userMessage: 'Threads did not accept the carousel. Please try again.',
category: ErrorCategory::ServerError,
);
}
// Step 3: Publish carousel
@ -244,7 +263,10 @@ private function publishContainer(string $userId, string $accessToken, string $c
$mediaId = $publishResponse->json()['id'] ?? null;
if (! $mediaId) {
throw new \Exception('Threads publish failed: no media ID returned');
throw new ThreadsPublishException(
userMessage: 'Threads did not accept the post. Please publish again.',
category: ErrorCategory::ServerError,
);
}
// Get permalink
@ -289,14 +311,20 @@ private function waitForMediaProcessing(string $containerId, string $accessToken
if ($status === 'ERROR') {
$errorMessage = data_get($data, 'error_message', 'Unknown error');
throw new \Exception('Threads media processing failed: '.$errorMessage);
throw new ThreadsPublishException(
userMessage: 'Threads media processing failed. Please try a different file.',
category: ErrorCategory::ServerError,
);
}
sleep(3);
}
Log::warning('Threads media processing timeout', ['container_id' => $containerId]);
throw new \Exception('Threads media processing timeout after '.$maxAttempts.' attempts');
throw new ThreadsPublishException(
userMessage: 'Threads took too long to process the media. Please try again.',
category: ErrorCategory::ServerError,
);
}
private function handleApiError(Response $response): never

View file

@ -72,7 +72,10 @@ public function publish(PostPlatform $postPlatform): array
}
if (empty($content) && empty($mediaIds)) {
throw new \Exception('X posts require either text or media. Please add content to your post.');
throw new XPublishException(
userMessage: 'X posts require either text or media. Please add content to your post.',
category: ErrorCategory::MediaFormat,
);
}
$response = $this->getHttpClient()
@ -115,7 +118,10 @@ private function uploadMedia($mediaItem): ?array
$downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url);
if ($downloadResponse->failed()) {
throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status());
throw new XPublishException(
userMessage: 'Could not fetch the media to upload to X. Please try again.',
category: ErrorCategory::ServerError,
);
}
// Recover the MIME from the downloaded bytes when the item carries
@ -215,7 +221,10 @@ private function chunkedUpload(string $tempFile, int $totalBytes, string $mimeTy
$mediaId = $initData['data']['id'] ?? $initData['media_id'] ?? null;
if (! $mediaId) {
throw new \Exception('No media_id returned from INIT');
throw new XPublishException(
userMessage: 'X did not accept the media upload. Please try again.',
category: ErrorCategory::ServerError,
);
}
// APPEND - Read from temp file in 1MB chunks. Matches the

View file

@ -4,6 +4,7 @@
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\LinkedInPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
use App\Models\PostPlatform;
@ -789,7 +790,7 @@ protected function processingPollSeconds(): int
});
expect(fn () => $this->publisher->publish($this->postPlatform))
->toThrow(Exception::class, 'missing uploadUrl or document URN');
->toThrow(LinkedInPublishException::class, 'did not accept the document upload');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));
});