From 8985b2ffd7c8d6e9cf726f630f39ce6e8f00df79 Mon Sep 17 00:00:00 2001 From: Toby Vincent Date: Sun, 13 Feb 2022 21:14:33 -0600 Subject: refactor: add error handling to libraries refactor libraries from using anyhow to explicitly handling errors --- zoned/src/api.rs | 18 ++++++++++-------- zoned/src/lib.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 8 deletions(-) (limited to 'zoned/src') diff --git a/zoned/src/api.rs b/zoned/src/api.rs index d36d2e2..fa98562 100644 --- a/zoned/src/api.rs +++ b/zoned/src/api.rs @@ -7,6 +7,8 @@ use rocket_okapi::{ }; use zone_core::{Container, PartialEqOrDefault}; +use crate::{Error, Result}; + /// # Test endpoint /// /// Returns a list of containers based on the query. @@ -34,22 +36,22 @@ pub fn container_list(container: Container) -> Json> { } /// Create container +/// +/// Creates a new container volume from the provided container json data #[openapi(tag = "Container")] #[post("/container", data = "")] fn create_container( container: Json, zfs_config: &State, -) -> Json { - let container = zone_zfs::create_file_system( +) -> Result> { + zone_zfs::create_file_system( container.template.clone(), format!("{}-{}", container.user, container.id), zfs_config, - ); - - match container { - Ok(f) => Json(Container::try_from(f).expect("failed to convert")), - Err(_err) => todo!("Respond with error message"), - } + )? + .try_into() + .map_err(Error::from) + .map(Container::into) } pub fn build_rocket(config: crate::Config) -> Rocket { diff --git a/zoned/src/lib.rs b/zoned/src/lib.rs index f17530f..4784ff5 100644 --- a/zoned/src/lib.rs +++ b/zoned/src/lib.rs @@ -1,4 +1,56 @@ +use rocket::{ + http::Status, + response::{self, Responder}, + Request, +}; +use rocket_okapi::{ + gen::OpenApiGenerator, okapi::openapi3::Responses, response::OpenApiResponderInner, + util::ensure_status_code_exists, +}; use serde::{Deserialize, Serialize}; +use thiserror::Error; +use zone_core::Container; + +type Result = std::result::Result; + +#[derive(Error, Debug)] +pub enum Error { + #[error("Container Error {0:?}")] + Container(Container), + + #[error("ZFS Error {source:?}")] + ZFS { + #[from] + source: zone_zfs::Error, + }, + + #[error("NSpawn Error {source:?}")] + Nspawn { + #[from] + source: zone_nspawn::Error, + }, + + #[error(transparent)] + Other(#[from] anyhow::Error), +} + +impl<'r, 'o: 'r> Responder<'r, 'o> for Error { + fn respond_to(self, req: &'r Request<'_>) -> response::Result<'o> { + // https://stuarth.github.io/rocket-error-handling/ + // match self { + // _ => Status::InternalServerError.respond_to(req), + // } + Status::InternalServerError.respond_to(req) + } +} + +impl OpenApiResponderInner for Error { + fn responses(_gen: &mut OpenApiGenerator) -> rocket_okapi::Result { + let mut responses = Responses::default(); + ensure_status_code_exists(&mut responses, 500); + Ok(responses) + } +} #[derive(Default, Serialize, Deserialize)] pub struct Config { -- cgit v1.2.3-70-g09d2