Skip to main content

Problem

Struct Problem 

Source
pub struct Problem {
    pub type_uri: Option<String>,
    pub title: Option<String>,
    pub status: Option<u16>,
    pub detail: Option<String>,
    pub instance: Option<String>,
    pub extensions: Map<String, Value>,
    /* private fields */
}
Expand description

An RFC 7807 Problem Details object.

Represents a structured error response per RFC 7807. All standard fields are optional and omitted from JSON when None. Extension fields are flattened into the top-level JSON object.

§Internal Cause

Use Problem::with_cause to attach a diagnostic error that is never serialized to JSON. This is essential for 5xx errors where you want to log the root cause server-side without exposing it to clients.

§Example

use rust_rfc7807::Problem;

let problem = Problem::bad_request()
    .title("Invalid input")
    .detail("The 'email' field is required");

let json = serde_json::to_value(&problem).unwrap();
assert_eq!(json["status"], 400);
assert_eq!(json["title"], "Invalid input");

Fields§

§type_uri: Option<String>

A URI reference that identifies the problem type. Defaults to "about:blank" per RFC 7807 when absent.

§title: Option<String>

A short, human-readable summary of the problem type.

§status: Option<u16>

The HTTP status code for this occurrence of the problem.

§detail: Option<String>

A human-readable explanation specific to this occurrence.

§instance: Option<String>

A URI reference that identifies this specific occurrence.

§extensions: Map<String, Value>

Extension fields beyond the RFC 7807 standard fields.

Implementations§

Source§

impl Problem

Source

pub fn new(status: u16) -> Self

Create a new problem with the given HTTP status code.

Per RFC 7807 §4.2, when no type is set the problem type defaults to "about:blank", and the title SHOULD match the HTTP status phrase. This constructor sets the title automatically.

use rust_rfc7807::Problem;

let p = Problem::new(429);
assert_eq!(p.status, Some(429));
assert_eq!(p.title.as_deref(), Some("Too Many Requests"));
Source

pub fn bad_request() -> Self

400 Bad Request.

Source

pub fn unauthorized() -> Self

401 Unauthorized.

Source

pub fn forbidden() -> Self

403 Forbidden.

Source

pub fn not_found() -> Self

404 Not Found.

Source

pub fn conflict() -> Self

409 Conflict.

Source

pub fn validation() -> Self

422 Unprocessable Entity with validation defaults.

Sets status to 422, type to "validation_error", and title to "Validation failed". Add field errors with push_error and push_error_code.

use rust_rfc7807::Problem;

let p = Problem::validation()
    .push_error("email", "is required");

let json = serde_json::to_value(&p).unwrap();
assert_eq!(json["status"], 422);
assert_eq!(json["type"], "validation_error");
Source

pub fn unprocessable_entity() -> Self

422 Unprocessable Entity (without validation defaults).

Source

pub fn too_many_requests() -> Self

429 Too Many Requests.

Source

pub fn internal_server_error() -> Self

500 Internal Server Error.

Returns a problem with safe generic defaults:

  • title: "Internal Server Error"
  • detail: "An unexpected error occurred."

Use with_cause to attach a diagnostic error for server-side logging without leaking it to clients.

Source§

impl Problem

Source

pub fn type_(self, type_uri: impl Into<String>) -> Self

Set the problem type URI.

The method is named type_ because type is a Rust keyword.

Source

pub fn title(self, title: impl Into<String>) -> Self

Set the title.

Source

pub fn status(self, status: u16) -> Self

Override the HTTP status code.

Source

pub fn detail(self, detail: impl Into<String>) -> Self

Set the public detail message.

Source

pub fn instance(self, instance: impl Into<String>) -> Self

Set the instance URI.

Source

pub fn code(self, code: impl Into<String>) -> Self

Set the "code" extension field — a stable string code for clients.

Source

pub fn trace_id(self, trace_id: impl Into<String>) -> Self

Set the "trace_id" extension field.

Source

pub fn request_id(self, request_id: impl Into<String>) -> Self

Set the "request_id" extension field.

Source

pub fn extension(self, key: impl Into<String>, value: impl Into<Value>) -> Self

Add an arbitrary extension field.

Source

pub fn push_error( self, field: impl Into<String>, message: impl Into<String>, ) -> Self

Append a field-level validation error.

Creates or appends to the "errors" extension array.

Source

pub fn push_error_code( self, field: impl Into<String>, message: impl Into<String>, code: impl Into<String>, ) -> Self

Append a field-level validation error with an error code.

Creates or appends to the "errors" extension array.

Source

pub fn errors(self, items: Vec<ValidationItem>) -> Self

Replace the "errors" extension with a complete list of validation items.

Source

pub fn with_cause(self, err: impl Error + Send + Sync + 'static) -> Self

Attach an internal cause for server-side diagnostics.

The cause is never serialized to JSON. Access it via internal_cause for logging.

Source

pub fn with_cause_str(self, message: impl Into<String>) -> Self

Attach a string message as the internal cause.

Convenience alternative to with_cause when you don’t have a typed error.

Source§

impl Problem

Source

pub const ABOUT_BLANK: &'static str = "about:blank"

The default problem type URI per RFC 7807 §4.2.

When the "type" member is absent, its value is assumed to be "about:blank", indicating that the problem has no additional semantics beyond the HTTP status code.

Source

pub fn get_type(&self) -> &str

Returns the effective problem type URI.

Returns the "type" value if set, or ABOUT_BLANK per RFC 7807 §4.2 when absent.

Source

pub fn status_code(&self) -> u16

Returns the HTTP status code, defaulting to 500 if not set.

Source

pub fn is_server_error(&self) -> bool

Returns true if the status code is 5xx.

Source

pub fn get_code(&self) -> Option<&str>

Returns the "code" extension value, if set.

Source

pub fn get_trace_id(&self) -> Option<&str>

Returns the "trace_id" extension value, if set.

Source

pub fn internal_cause(&self) -> Option<&(dyn Error + Send + Sync)>

Returns the internal cause message, if set.

This value is never included in serialized output and is intended for server-side logging only.

Source

pub fn to_json_string_pretty(&self) -> String

Serialize to a pretty-printed JSON string. Useful in tests and debugging.

Trait Implementations§

Source§

impl Clone for Problem

Source§

fn clone(&self) -> Problem

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Problem

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Problem

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Problem

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Problem

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Problem

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl IntoProblem for Problem

Source§

fn into_problem(self) -> Problem

Convert this value into a Problem instance.
Source§

impl Serialize for Problem

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,