Struct poem::error::Error

source ·
pub struct Error { /* private fields */ }
Expand description

General response error.

Create from any error types

use poem::{error::InternalServerError, handler, Result};

#[handler]
async fn index() -> Result<String> {
    Ok(std::fs::read_to_string("example.txt").map_err(InternalServerError)?)
}

Create you own error type

use poem::{error::ResponseError, handler, http::StatusCode, Endpoint, Request, Result};

#[derive(Debug, thiserror::Error)]
#[error("my error")]
struct MyError;

impl ResponseError for MyError {
    fn status(&self) -> StatusCode {
        StatusCode::BAD_GATEWAY
    }
}

fn do_something() -> Result<(), MyError> {
    Err(MyError)
}

#[handler]
async fn index() -> Result<()> {
    Ok(do_something()?)
}

let resp = index.get_response(Request::default()).await;
assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
assert_eq!(resp.into_body().into_string().await.unwrap(), "my error");

Custom error response

use poem::{error::ResponseError, handler, http::StatusCode, Response, Result, Request, Body, Endpoint};

#[derive(Debug, thiserror::Error)]
#[error("my error")]
struct MyError;

impl ResponseError for MyError {
    fn status(&self) -> StatusCode {
        StatusCode::BAD_GATEWAY
    }

    fn as_response(&self) -> Response {
        let body = Body::from_json(serde_json::json!({
            "code": 1000,
            "message": self.to_string(),
        })).unwrap();
        Response::builder().status(self.status()).body(body)
    }
}

fn do_something() -> Result<(), MyError> {
    Err(MyError)
}

#[handler]
async fn index() -> Result<()> {
    Ok(do_something()?)
}

let resp = index.get_response(Request::default()).await;
assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
assert_eq!(resp.into_body().into_json::<serde_json::Value>().await.unwrap(),
serde_json::json!({
    "code": 1000,
    "message": "my error",
}));

Downcast the error to concrete error type

use poem::{error::NotFoundError, Error};

let err: Error = NotFoundError.into();

assert!(err.is::<NotFoundError>());
assert_eq!(err.downcast_ref::<NotFoundError>(), Some(&NotFoundError));

Implementations§

source§

impl Error

source

pub fn new<T: StdError + Send + Sync + 'static>( err: T, status: StatusCode ) -> Self

Create a new error object from any error type with a status code.

source

pub fn from_response(resp: Response) -> Self

Create a new error object from response.

source

pub fn from_status(status: StatusCode) -> Self

create a new error object from status code.

source

pub fn from_string(msg: impl Into<String>, status: StatusCode) -> Self

Create a new error object from a string with a status code.

source

pub fn downcast_ref<T: StdError + Send + Sync + 'static>(&self) -> Option<&T>

Downcast this error object by reference.

source

pub fn downcast<T: StdError + Send + Sync + 'static>(self) -> Result<T, Error>

Attempts to downcast the error to a concrete error type.

source

pub fn is<T: StdError + Debug + Send + Sync + 'static>(&self) -> bool

Returns true if the error type is the same as T.

source

pub fn into_response(self) -> Response

Consumes this to return a response object.

source

pub fn has_source(&self) -> bool

Returns whether the error has a source or not.

source

pub fn set_data(&mut self, data: impl Send + Sync + 'static)

Inserts a value to extensions

Passed to Response::extensions when this error converted to Response.

Examples
let mut err = Error::from_status(StatusCode::BAD_REQUEST);
err.set_data(100i32);

let resp = err.into_response();
assert_eq!(resp.data::<i32>(), Some(&100));
source

pub fn data<T: Send + Sync + 'static>(&self) -> Option<&T>

Get a reference from extensions

source

pub fn status(&self) -> StatusCode

Get the status code of the error

source

pub fn is_from_response(&self) -> bool

Returns true if the error was created from the response

source

pub fn set_error_message(&mut self, msg: impl Into<String>)

Set the error message

Trait Implementations§

source§

impl Debug for Error

source§

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

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

impl Display for Error

source§

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

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

impl From<(StatusCode, Box<dyn Error + Send + Sync>)> for Error

source§

fn from((status, err): (StatusCode, Box<dyn StdError + Send + Sync>)) -> Self

Converts to this type from the input type.
source§

impl From<(StatusCode, Error)> for Error

source§

fn from((status, err): (StatusCode, Error)) -> Self

Converts to this type from the input type.
source§

impl From<(StatusCode, Report)> for Error

source§

fn from((status, err): (StatusCode, Report)) -> Self

Converts to this type from the input type.
source§

impl From<Box<dyn Error + Send + Sync>> for Error

source§

fn from(err: Box<dyn StdError + Send + Sync>) -> Self

Converts to this type from the input type.
source§

impl From<Error> for Error

source§

fn from(err: Error) -> Self

Converts to this type from the input type.
source§

impl From<Infallible> for Error

source§

fn from(_: Infallible) -> Self

Converts to this type from the input type.
source§

impl From<Report> for Error

source§

fn from(err: Error) -> Self

Converts to this type from the input type.
source§

impl From<StatusCode> for Error

source§

fn from(status: StatusCode) -> Self

Converts to this type from the input type.
source§

impl<T: ResponseError + StdError + Send + Sync + 'static> From<T> for Error

source§

fn from(err: T) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32 ) -> TaggedParser<'a, Implicit, Self, E>

source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> FutureExt for T

source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere 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

§

type Output = T

Should always be Self
source§

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

source§

default fn to_string(&self) -> String

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

impl<T> TowerCompatExt for T

source§

fn compat<ResBody, Err, Fut>(self) -> TowerCompatEndpoint<Self>where ResBody: HttpBody + Send + 'static, ResBody::Data: Into<Bytes> + Send + 'static, ResBody::Error: StdError + Send + Sync + 'static, Err: Into<Error>, Self: Service<Request<Body>, Response = Response<ResBody>, Error = Err, Future = Fut> + Clone + Send + Sync + Sized + 'static, Fut: Future<Output = Result<Response<ResBody>, Err>> + Send + 'static,

Available on crate feature tower-compat only.
Converts a tower service to a poem endpoint.
source§

impl<L> TowerLayerCompatExt for L

source§

fn compat(self) -> TowerCompatMiddleware<Self>where Self: Sized,

Available on crate feature tower-compat only.
Converts a tower layer to a poem middleware.
source§

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

§

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 Twhere U: TryFrom<T>,

§

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.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more