1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
// Copyright 2017 Telefónica Germany Next GmbH. See the COPYRIGHT file at // the top-level directory of this distribution // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #![allow(unused_doc_comment)] //! Geeny Hub SDK Error Types //! //! These error types are generated by [Error Chain](https://docs.rs/error-chain/). //! These types can be combined with other crates using `error_chain` in the following way: //! //! ```rust //! #[macro_use] //! extern crate error_chain; //! extern crate hub_sdk; //! //! mod your_error { //! use hub_sdk::errors; //! //! error_chain!{ //! links { //! GeenyHub(errors::Error, errors::ErrorKind); //! } //! } //! } //! //! fn main() {} //! ``` //! //! Additionally, `Error` implements the `Responder` trait from Rocket, and will produce //! a JSON return value with error code 400 if returned from a route handler in Rocket. #[cfg(feature = "rest-service")] use std::io::Cursor; #[cfg(feature = "rest-service")] use std::fmt::Write; #[cfg(feature = "rest-service")] use log; #[cfg(feature = "rest-service")] use rocket::request::Request; #[cfg(feature = "rest-service")] use rocket::response::{Responder, Response}; #[cfg(feature = "rest-service")] use rocket::http::{ContentType, Status}; use mvdb::errors as merr; use geeny_api::errors as gerr; // TODO DI-234 - Proper enumeration of errors error_chain!{ links { Mvdb(merr::Error, merr::ErrorKind); GeenyApi(gerr::Error, gerr::ErrorKind); } } // Implement `Responder` for `error_chain`'s `Error` type #[cfg(feature = "rest-service")] impl<'r> Responder<'r> for Error { /// Implement `respond_to` in order to allow route handlers to generate a JSON response /// in the case of error. Please see [this blog post](https://jamesmunns.com/update/2017/07/22/rocket-plus-error-chain.html) /// for more information fn respond_to(self, _: &Request) -> ::std::result::Result<Response<'r>, Status> { // Render the whole error chain to a single string let mut rslt = String::new(); write!(rslt, "Error: {}", self).unwrap(); for ce in self.iter().skip(1) { write!(rslt, ", caused by: {}", ce).unwrap(); } log::error!("{}", rslt); // Create JSON response let resp = json!({ "status": "failure", "message": rslt, }).to_string(); // Respond. The `Ok` here is a bit of a misnomer. It means we // successfully created an error response Ok( Response::build() .status(Status::BadRequest) .header(ContentType::JSON) .sized_body(Cursor::new(resp)) .finalize(), ) } }