The Exception Handling Flow
- Occurrence: An exception or error is thrown during the request lifecycle (routing, middleware, or controller).
- Catch: If the exception is not caught by your code, it is intercepted by the global exception handler registered during bootstrapping.
- Response: The exception handler generates an
InternalServerErrorApivalkResponse(HTTP 500) and renders it using theJsonRenderer.
Built-in Exception Handler
Apivalk includes a standardApivalkExceptionHandler class that provides a safe fallback for all unhandled errors.
ApivalkExceptionHandler::handle(\Throwable $t)
This static method is designed to be used with PHP’s set_exception_handler. It performs the following actions:
- Creates a new instance of
InternalServerErrorApivalkResponse. - Uses the
JsonRendererto output the response directly to the client.
Configuring the Exception Handler
By default, Apivalk does not register an exception handler unless you provide one in theApivalkConfiguration.
Using the Built-in Handler
To use the built-in handler, pass it as a callable to the configuration:Custom Exception Handling
You can provide anycallable as an exception handler. This is useful for adding logging, Sentry/Flare integration, or environment-specific error details.
InternalServerErrorApivalkResponse
This specialized response object is used for 500 errors. It ensures that even errors follow the documented API structure.- Status Code: 500 Internal Server Error.
- Default Message: “We’ve run into an unknown error, please try again later.”
- Structure:
Best Practices
- Always Register a Handler: In production, always register an exception handler to prevent leaking sensitive server information via PHP’s default error output.
- Contextual Logging: Use a custom handler to log the full stack trace of exceptions to your logging service before rendering the generic error response to the user.
- Graceful Degradation: Ensure your exception handler itself is extremely robust and does not throw further exceptions.