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
impl Error
sourcepub fn new<T: StdError + Send + Sync + 'static>(
err: T,
status: StatusCode
) -> Self
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.
sourcepub fn from_response(resp: Response) -> Self
pub fn from_response(resp: Response) -> Self
Create a new error object from response.
sourcepub fn from_status(status: StatusCode) -> Self
pub fn from_status(status: StatusCode) -> Self
create a new error object from status code.
sourcepub fn from_string(msg: impl Into<String>, status: StatusCode) -> Self
pub fn from_string(msg: impl Into<String>, status: StatusCode) -> Self
Create a new error object from a string with a status code.
sourcepub fn downcast_ref<T: StdError + Send + Sync + 'static>(&self) -> Option<&T>
pub fn downcast_ref<T: StdError + Send + Sync + 'static>(&self) -> Option<&T>
Downcast this error object by reference.
sourcepub fn downcast<T: StdError + Send + Sync + 'static>(self) -> Result<T, Error>
pub fn downcast<T: StdError + Send + Sync + 'static>(self) -> Result<T, Error>
Attempts to downcast the error to a concrete error type.
sourcepub fn is<T: StdError + Debug + Send + Sync + 'static>(&self) -> bool
pub fn is<T: StdError + Debug + Send + Sync + 'static>(&self) -> bool
Returns true
if the error type is the same as T
.
sourcepub fn into_response(self) -> Response
pub fn into_response(self) -> Response
Consumes this to return a response object.
sourcepub fn has_source(&self) -> bool
pub fn has_source(&self) -> bool
Returns whether the error has a source or not.
sourcepub fn status(&self) -> StatusCode
pub fn status(&self) -> StatusCode
Get the status code of the error
sourcepub fn is_from_response(&self) -> bool
pub fn is_from_response(&self) -> bool
Returns true
if the error was created from the response
sourcepub fn set_error_message(&mut self, msg: impl Into<String>)
pub fn set_error_message(&mut self, msg: impl Into<String>)
Set the error message
Trait Implementations§
source§impl From<(StatusCode, Error)> for Error
impl From<(StatusCode, Error)> for Error
source§fn from((status, err): (StatusCode, Error)) -> Self
fn from((status, err): (StatusCode, Error)) -> Self
Converts to this type from the input type.
source§impl From<(StatusCode, Report)> for Error
impl From<(StatusCode, Report)> for Error
source§fn from((status, err): (StatusCode, Report)) -> Self
fn from((status, err): (StatusCode, Report)) -> Self
Converts to this type from the input type.
source§impl From<Infallible> for Error
impl From<Infallible> for Error
source§fn from(_: Infallible) -> Self
fn from(_: Infallible) -> Self
Converts to this type from the input type.
source§impl From<StatusCode> for Error
impl From<StatusCode> for Error
source§fn from(status: StatusCode) -> Self
fn from(status: StatusCode) -> 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§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere T: 'a,
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
source§impl<T> FutureExt for T
impl<T> FutureExt for T
source§fn with_context(self, otel_cx: Context) -> WithContext<Self>
fn with_context(self, otel_cx: Context) -> WithContext<Self>
source§fn with_current_context(self) -> WithContext<Self>
fn with_current_context(self) -> WithContext<Self>
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> TowerCompatExt for T
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,
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.