Interview frequency: …
Short answer
Customize exception handling in bootstrap/app.php or Handler with renderable to turn errors such as ModelNotFoundException into formatted JSON responses.
Explanation
By default, Laravel may return HTML pages or sensitive code details when errors occur. Configure the exception handler to recognize API requests with $request->expectsJson() and return a consistent structure containing an error code and clear message, while hiding the Stack Trace in production.
Code example
// bootstrap/app.php (Laravel 11)
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (NotFoundHttpException $e, Request $request) {
if ($request->is('api/*')) {
return response()->json(['message' => 'Resource not found'], 404);
}
});
})Common mistakes
- Leaking SQL Exception details and table and column names to users in production.
Follow-up questions
- What are API Resources in Laravel, and why are they better than returning Eloquent models directly as JSON?
- How do you isolate validation and authorization logic in Laravel Form Request classes?