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

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

Create a new error object from response.

create a new error object from status code.

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

Downcast this error object by reference.

Attempts to downcast the error to a concrete error type.

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

Consumes this to return a response object.

Returns whether the error has a source or not.

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));

Get a reference from extensions

Get the status code of the error

Returns true if the error was created from the response

Trait Implementations

Formats the value using the given formatter. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Attaches the current Context to this type, returning a WithContext wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

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

Should always be Self
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more