Turn domain failures into useful responses
Keep expected conflicts separate from unexpected faults.
Name the failure
A booking conflict, a missing record, and a database outage need different treatment. Give expected domain outcomes named exceptions or result types. A controller can map them to stable status codes and messages, while unexpected exceptions reach monitoring. Do not turn every exception into a generic 200 response with an error string.
Preserve the boundary
The domain service should say that a slot is unavailable, not know whether the caller is HTTP, a queue job, or a command. At the HTTP edge, return a safe 409 response. At a queue edge, decide whether the event should be retried. This keeps a useful core when delivery channels change.
try { $booking = $service->reserve($requestData); }
catch (SlotUnavailable $e) {
return response()->json(['error' => 'slot_unavailable'], 409);
}
Test the side effect
For conflict, assert both the response and that no booking or charge was created. For an unexpected repository failure, assert the failure is not misreported as a user mistake. Keep error details out of public responses, but attach a correlation ID to logs so operators can find the underlying cause.
Check your understanding
Why should a service return 'slot unavailable' instead of HTTP 409 directly?
Show explanation
The service expresses a business outcome; the HTTP boundary chooses its transport-specific representation.
You can read for free. Create an account to save your progress.
← Previous lesson: Keep controllers thin and HTTP errors clear Next lesson: Use small objects to protect invariants →Put this lesson into practice
A practice activity at this level in the same module.
Try: Extract business logic from a fat controllerFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.