ErrorResponse

Struct ErrorResponse 

Source
pub struct ErrorResponse {
    pub status: u16,
    pub code: AppCode,
    pub message: String,
    pub details: Option<String>,
    pub retry: Option<RetryAdvice>,
    pub www_authenticate: Option<String>,
}
Expand description

Public, wire-level error payload for HTTP APIs.

This type is serialized to JSON (or another transport format) and forms part of the stable wire contract between services and clients.

Fields§

§status: u16

HTTP status code (e.g. 404, 422, 500).

§code: AppCode

Stable machine-readable error code.

§message: String

Human-oriented, non-sensitive message.

§details: Option<String>
Available on non-crate feature serde_json only.

Optional textual details (if serde_json is not enabled).

§retry: Option<RetryAdvice>

Optional retry advice. If present, integrations set the Retry-After header.

§www_authenticate: Option<String>

Optional authentication challenge. If present, integrations set the WWW-Authenticate header.

Example value: Bearer realm="api", error="invalid_token".

Implementations§

Source§

impl ErrorResponse

Source

pub fn new( status: u16, code: AppCode, message: impl Into<String>, ) -> AppResult<Self>

Construct a new ErrorResponse with a status code, a stable AppCode, and a public message.

§Errors

Returns AppError if status is not a valid HTTP status code.

Source

pub fn status_code(&self) -> StatusCode

Convert numeric status into StatusCode.

Invalid codes default to StatusCode::INTERNAL_SERVER_ERROR.

§Examples
use http::StatusCode;
use masterror::{AppCode, ErrorResponse};

let resp = ErrorResponse::new(404, AppCode::NotFound, "missing").expect("status");
assert_eq!(resp.status_code(), StatusCode::NOT_FOUND);
Source

pub fn internal(&self) -> ErrorResponseFormatter<'_>

Formatter exposing internals for diagnostic logs.

Source§

impl ErrorResponse

Source

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

Available on non-crate feature serde_json only.

Attach plain-text details (available when serde_json is disabled).

Source§

impl ErrorResponse

Legacy constructor retained for migration purposes.

Deprecated: prefer ErrorResponse::new with an AppCode argument.

§Examples

#[allow(deprecated)]
let response = ErrorResponse::new_legacy(404, "Not found");
assert_eq!(response.status, 404);
assert_eq!(response.message, "Not found");
Source

pub fn new_legacy(status: u16, message: impl Into<String>) -> Self

👎Deprecated: Use new(status, code, message) instead

Construct an error response with only (status, message).

This defaults the code to AppCode::Internal. Kept temporarily to ease migration from versions prior to 0.3.0.

§Examples
#[allow(deprecated)]
let response = ErrorResponse::new_legacy(500, "Internal error");
assert_eq!(response.status, 500);
assert_eq!(response.code, AppCode::Internal);
assert_eq!(response.message, "Internal error");
Source§

impl ErrorResponse

Source

pub fn with_retry_after_secs(self, secs: u64) -> Self

Attach retry advice (number of seconds).

See with_retry_after_duration for using a Duration. When present, integrations set the Retry-After header automatically.

§Examples
use masterror::{AppCode, ErrorResponse};

let resp = ErrorResponse::new(503, AppCode::Internal, "unavailable")
    .expect("status")
    .with_retry_after_secs(120);

assert_eq!(resp.retry.expect("retry").after_seconds, 120);
Source

pub fn with_retry_after_duration(self, dur: Duration) -> Self

Attach retry advice as a Duration.

Equivalent to with_retry_after_secs. When present, integrations set the Retry-After header automatically.

§Examples
use core::time::Duration;

use masterror::{AppCode, ErrorResponse};

let resp = ErrorResponse::new(503, AppCode::Internal, "retry later")
    .expect("status")
    .with_retry_after_duration(Duration::from_secs(60));
assert_eq!(resp.retry.expect("retry").after_seconds, 60);
Source

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

Attach an authentication challenge string.

When present, integrations set the WWW-Authenticate header automatically.

§Examples
use masterror::{AppCode, ErrorResponse};

let resp = ErrorResponse::new(401, AppCode::Unauthorized, "auth required")
    .expect("status")
    .with_www_authenticate("Bearer realm=\"api\"");

assert_eq!(
    resp.www_authenticate.as_deref(),
    Some("Bearer realm=\"api\"")
);

Trait Implementations§

Source§

impl Clone for ErrorResponse

Source§

fn clone(&self) -> ErrorResponse

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 ErrorResponse

Source§

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

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

impl<'de> Deserialize<'de> for ErrorResponse

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 ErrorResponse

Format ErrorResponse for logging and debugging.

Produces a concise format: "{status} {code:?}: {message}".

§Examples

use masterror::{AppCode, ErrorResponse};

let resp = ErrorResponse::new(404, AppCode::NotFound, "user not found").expect("status");

let formatted = resp.to_string();
assert!(formatted.contains("404"));
assert!(formatted.contains("NOT_FOUND"));
assert!(formatted.contains("user not found"));
Source§

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

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

impl From<&Error> for ErrorResponse

Convert borrowed AppError to ErrorResponse.

Clones the error’s message and metadata, leaving the original error intact. Respects MessageEditPolicy for message visibility.

§Examples

use masterror::{AppError, ErrorResponse};

let err = AppError::conflict("resource exists");
let resp: ErrorResponse = (&err).into();

assert_eq!(resp.message, "resource exists");
// Original error remains intact
assert_eq!(err.message.as_deref(), Some("resource exists"));
Source§

fn from(err: &AppError) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for ErrorResponse

Convert owned AppError to ErrorResponse.

Consumes the error, transferring ownership of message and metadata. Respects MessageEditPolicy for message visibility.

§Examples

use masterror::{AppError, AppErrorKind, ErrorResponse};

let err = AppError::validation("invalid email");
let resp: ErrorResponse = err.into();

assert_eq!(resp.status, AppErrorKind::Validation.http_status());
assert_eq!(resp.message, "invalid email");
Source§

fn from(err: AppError) -> Self

Converts to this type from the input type.
Source§

impl Serialize for ErrorResponse

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> Same for T

Source§

type Output = T

Should always be Self
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>,