Structured error handling with multi-format output.
Define errors once and render them to JSON, GraphQL, HTML, or plain text.
Quick Start
use ;
use Diagnostic;
let error = InvalidCredentials ;
let config = default;
// Render to different formats
let json = error.to_json.unwrap;
let graphql = error.to_graphql.unwrap;
let jsonrpc = error.to_jsonrpc.unwrap;
let html = error.to_html;
let text = error.to_text;
Defining Errors
Errors require three derives: Debug, Error, and Diagnostic.
Attributes
Error Message
Use #[error("...")] to define the error message. Field interpolation is supported:
ConnectionFailed ,
Error Code
Use #[diagnostic(code(...))] to define a unique error code. Codes must have
at least two :: separated segments, all lowercase:
Extension Fields
Mark fields with #[extension] to include them in JSON and GraphQL output:
InvalidPort ,
HTTP Status
Specify an HTTP status code (defaults to 500):
NotFound,
HTTP Headers
Mark fields to be returned as HTTP response headers. Supported types are u16, u32,
u64, i16, i32, i64, bool, and HeaderValue:
RateLimitExceeded ,
Header names are validated at compile time against RFC 7230. Headers are
automatically set when using [tower_http::ErrorLayer]. For Option<T> fields,
the header is only included when the value is Some.
JSON-RPC Code
Specify a JSON-RPC 2.0 error code (defaults to -32000, "Server error"):
InvalidParams ,
Reserved JSON-RPC codes:
-32700: Parse error-32600: Invalid Request-32601: Method not found-32602: Invalid params-32603: Internal error-32000to-32099: Server error (available for application use)
Help Text and URLs
Provide additional context for users:
Error Chaining
Use #[source] to chain errors, or #[from] to also generate a From impl:
DatabaseError ,
Dynamic Dispatch
Format any std::error::Error using the extension traits:
use ;