wasmtime_wasi_http/
error.rsuse crate::bindings::http::types::ErrorCode;
use std::error::Error;
use std::fmt;
use wasmtime_wasi::ResourceTableError;
pub type HttpResult<T, E = HttpError> = Result<T, E>;
#[repr(transparent)]
pub struct HttpError {
err: anyhow::Error,
}
impl HttpError {
pub fn trap(err: impl Into<anyhow::Error>) -> HttpError {
HttpError { err: err.into() }
}
pub fn downcast(self) -> anyhow::Result<ErrorCode> {
self.err.downcast()
}
pub fn downcast_ref(&self) -> Option<&ErrorCode> {
self.err.downcast_ref()
}
}
impl From<ErrorCode> for HttpError {
fn from(error: ErrorCode) -> Self {
Self { err: error.into() }
}
}
impl From<ResourceTableError> for HttpError {
fn from(error: ResourceTableError) -> Self {
HttpError::trap(error)
}
}
impl fmt::Debug for HttpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.err.fmt(f)
}
}
impl fmt::Display for HttpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.err.fmt(f)
}
}
impl Error for HttpError {}
pub(crate) fn dns_error(rcode: String, info_code: u16) -> ErrorCode {
ErrorCode::DnsError(crate::bindings::http::types::DnsErrorPayload {
rcode: Some(rcode),
info_code: Some(info_code),
})
}
pub(crate) fn internal_error(msg: String) -> ErrorCode {
ErrorCode::InternalError(Some(msg))
}
pub fn http_request_error(err: http::Error) -> ErrorCode {
if err.is::<http::uri::InvalidUri>() {
return ErrorCode::HttpRequestUriInvalid;
}
tracing::warn!("http request error: {err:?}");
ErrorCode::HttpProtocolError
}
pub fn hyper_request_error(err: hyper::Error) -> ErrorCode {
if let Some(cause) = err.source() {
if let Some(err) = cause.downcast_ref::<ErrorCode>() {
return err.clone();
}
}
tracing::warn!("hyper request error: {err:?}");
ErrorCode::HttpProtocolError
}
pub fn hyper_response_error(err: hyper::Error) -> ErrorCode {
if err.is_timeout() {
return ErrorCode::HttpResponseTimeout;
}
if let Some(cause) = err.source() {
if let Some(err) = cause.downcast_ref::<ErrorCode>() {
return err.clone();
}
}
tracing::warn!("hyper response error: {err:?}");
ErrorCode::HttpProtocolError
}