HTTP status exceptions
This repository includes a set of exception classes representing HTTP status responses.
They live under the GT\Http\ResponseStatusException namespaces and are grouped by response category:
ClientErrorRedirectionServerError
Why use exception classes for HTTP statuses?
Sometimes the clearest way to stop request processing is to throw an exception that already carries the intended HTTP status.
For example:
use GT\Http\ResponseStatusException\ClientError\HttpNotFound;
if(!$article) {
throw new HttpNotFound("Article not found");
}
That expresses intent much more clearly than a plain generic exception.
Common examples
Client errors:
HttpBadRequestHttpUnauthorizedHttpForbiddenHttpNotFoundHttpMethodNotAllowedHttpNotAcceptableHttpTooManyRequestsHttpUnprocessableEntity
Redirections:
HttpMovedPermanentlyHttpFoundHttpSeeOtherHttpTemporaryRedirectHttpPermanentRedirect
Server errors:
HttpInternalServerErrorHttpNotImplementedHttpBadGatewayServiceUnavailableHttpGatewayTimeout
Base classes
The status exceptions also have shared base types:
ResponseStatusExceptionClientErrorExceptionRedirectionExceptionServerErrorException
These are useful when you want to catch a whole category rather than one exact status.
use GT\Http\ResponseStatusException\ClientError\ClientErrorException;
try {
// ...
}
catch(ClientErrorException $error) {
// Handle any 4xx style response exception.
}
How the status code is exposed
Each class knows its own HTTP code through getHttpCode().
That means higher-level framework code can catch the exception and turn it into the correct response automatically.
[!NOTE] WebEngine makes direct use of these exception types. If page logic throws one of them, the framework can use the embedded HTTP code when generating the error response.
When not to use them
These classes are best for application flow that really should become a specific HTTP response.
They are not a substitute for every ordinary domain or validation exception in your codebase. If an error is not really “HTTP 404, Not Found” or “HTTP 403, Forbidden”, a normal exception class is usually the better fit.
Let’s see some Examples of this library in action.