pub trait ErrIntoHttpResponse: Error + Sized {
    // Provided method
    fn into_http_response(self) -> Result<Response<Bytes>, Box<dyn Error>> { ... }
}
Expand description

Trait describing how an error should be converted into a http::Response<Bytes>.

Provided Methods§

source

fn into_http_response(self) -> Result<Response<Bytes>, Box<dyn Error>>

Convert this error into a HTTP response.

The default implementation returns a response with status code 500 (Internal Server Error) and the Display implementation of Self inside the "error" field of a JSON object in the body.

Implementors may wish to override this if they wish to provide an alternative status code depending on, for example, the type of error returned from a resource call.

Example
use bytes::Bytes;
use grafana_plugin_sdk::backend;
use thiserror::Error;

#[derive(Debug, Error)]
enum ResourceError {
    #[error("HTTP error: {0}")]
    Http(#[from] http::Error),

    #[error("Path not found")]
    NotFound,
}

impl backend::ErrIntoHttpResponse for ResourceError {
    fn into_http_response(self) -> Result<http::Response<Bytes>, Box<dyn std::error::Error>> {
        let status = match &self {
            Self::Http(_) => http::StatusCode::INTERNAL_SERVER_ERROR,
            Self::NotFound => http::StatusCode::NOT_FOUND,
        };
        Ok(http::Response::builder()
            .status(status)
            .body(Bytes::from(serde_json::to_vec(
                &serde_json::json!({"error": self.to_string()}),
            )?))?)
    }
}

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl ErrIntoHttpResponse for Infallible

Implementors§