The documentation you are viewing is for an older version of this component.
Switch to the latest (v6) version.
Exceptions are a powerful mechanism for handling errors and other exceptional conditions that may occur during the execution of a script. They provide a way to manage errors in a structured and controlled manner, separating error-handling code from regular code.
When it comes to handling exceptions, Dotkernel API relies on the usage of easy-to-understand, problem-specific exceptions. Below we will list the available custom exceptions.
BadRequestException thrown whenidentity field)ConflictException thrown whenExpiredException thrown whenForbiddenException thrown whenGET /admin request)MethodNotAllowedException thrown whenPATCH /avatar request)NotFoundException thrown whenGET /resource-does-not-exist request)UnauthorizedException thrown whenGET /admin request)During a request, if there is no uncaught exception, Dotkernel API will return a JSON response with the data provided by the handler that processed the request.
Otherwise, it will build and send a response based on the exception thrown:
BadRequestException will return a 400 Bad Request responseUnauthorizedException will return a 401 Unauthorized responseForbiddenException will return a 403 Forbidden responseOutOfBoundsException and NotFoundException will return a 404 Not Found responseMethodNotAllowedException will return a 405 Method Not Allowed responseConflictException will return a 409 Conflict responseExpiredException will return a 410 Gone responseMailException, RuntimeException and the generic Exception will return a 500 Internal Server Error responseIn this example we will
CustomExceptionCustomException is encountered.Navigate to the directory src/App/src/Handler/Exception and create a PHP class called CustomException.php.
Open CustomException.php and add the following content:
<?php
declare(strict_types=1);
namespace Api\App\Exception;
use Exception;
class CustomException extends Exception
{
}
Save and close the file.
Open the file src/App/src/Handler/HomeHandler.php and at the beginning of the get method, place the following code:
throw new \Api\App\Exception\CustomException('some message');
Save and close the file.
Access your API's home page URL and make sure it returns 500 Internal Server Error HTTP status code and the following content:
{
"error": {
"messages": [
"some message"
]
}
}
Open the file src/App/src/Handler/HandlerTrait.php and locate the handle method.
Insert the following lines of code before the first catch statement:
} catch (\Api\App\Exception\CustomException $exception) {
return $this->errorResponse($exception->getMessage(), StatusCodeInterface::STATUS_IM_A_TEAPOT);
Save and close the file.
Access your API's home page URL, which should return the same content.
Notice that this time it returns 418 I'm a teapot HTTP status code.