Error handling
The library catches any exception derived from the ApiException class and converts it to a response. You can throw an ApiException at any time to halt the process.
TIP
To handle other exceptions, such as WireException, you need to specify custom handling function by calling handleException() method of the API instance. It receives exceptions thrown at any point of the request handling, including hooks, authenticators, and plugins. Without it, other exceptions are passed to ProcessWire, which renders its own error page. Read more about exception handling.
Example exception
throw new ApiException('Snap, crackle and pop!');The resulting JSON:
{
"error": "Snap, crackle and pop!"
}Exception response code
The default response code is 400. Use code() to specify a custom code.
throw (new ApiException('Snap, crackle and pop!'))->code(401);Additional top-level keys
Like responses, exceptions can also contain additional key-value pairs.
throw (new ApiException())->code(401)->with([
'login_url' => 'https://example.com/login',
]);The resulting JSON:
{
"login_url": "https://example.com/login"
}HTTP headers ^2.0
Use header() to set custom HTTP headers on the error response.
throw (new ApiException('Forbidden'))
->code(403)
->header('X-Reason', 'insufficient-permissions');Api404Exception
This can be used as a shorthand for an exception with a 404 response code.
throw new Api404Exception();