Errors
Errors use the same format and codes as the PHP package: see the PHP Errors page for the format and every built-in code.
How errors are rendered
The FusionStack service provider renders every error on the paths Config::error_paths lists (all of them by default) as a JSON:API error document with Content-Type: application/vnd.api+json. The framework's own errors are converted too:
| Framework error | Code |
|---|---|
InvalidInput, and validation failures from the Validate derive | validation_failed, with a source.pointer per field |
| An unknown route | not_found |
| A route without the method | method_not_allowed, with Allow |
ModelNotFound (with the database feature) | not_found, without naming the model |
| Any other status | The code for that status, such as too_many_requests |
| Any other error | server_error, with the detail An unexpected error occurred. |
Each error repeats the response's X-Request-Id in meta.request_id.
Built-in error codes
ApiErrorCode has every code in the error code table, with the same statuses, titles and descriptions. Both packages read them from spec/error-codes.json. ApiErrorCode::ALL lists them, and ApiErrorCode::for_status(status) gives the code for a status with no more specific one.
ApiError
ApiError is PHP's ApiException. Return it with into_error():
use fusion_stack::errors::{ApiError, ApiErrorCode};
return Err(ApiError::new(ApiErrorCode::Conflict, "Only pending and paid orders can be cancelled.")
.pointer("/data/attributes/status")
.meta("status", "shipped")
.into_error());| Method | What it adds |
|---|---|
ApiError::new(code, detail) | The code, its status and title, and the detail. |
ApiError::not_found() | A not_found error worded as the framework's. |
pointer(pointer) | source.pointer, a JSON pointer into the request body. |
parameter(name) | source.parameter, the query parameter at fault. |
header_source(name) | source.header, the request header at fault. |
link(name, url) | A link, such as about. |
meta(key, value) | A meta member. |
header(name, value) | A response header, such as Retry-After. |
into_error() | The error as a laravel::Error, for ? and Err. |
ApiError has no From conversion, because the framework already converts every error type into its own.
Your own error codes
Implement ErrorCode on your own type, and list it with Config::error_codes so the OpenAPI document includes it:
use fusion_stack::errors::ErrorCode;
#[derive(Debug)]
pub struct OrderNotCancellable;
impl ErrorCode for OrderNotCancellable {
fn code(&self) -> &str { "order_not_cancellable" }
fn status(&self) -> u16 { 409 }
fn title(&self) -> &str { "Order cannot be cancelled" }
fn description(&self) -> &str {
"The order has shipped or was already cancelled, so it cannot be cancelled."
}
}description is PHP's #[Description]; api:docs:lint lists codes without one.