response_http.rs 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. use crate::{errors::NetworkError, response::*};
  2. use actix_web::{body::Body, error::ResponseError, HttpResponse};
  3. use serde::Serialize;
  4. impl ResponseError for NetworkError {
  5. fn error_response(&self) -> HttpResponse {
  6. match self {
  7. NetworkError::InternalError(msg) => {
  8. let resp = FlowyResponse::from_msg(&msg, ServerCode::InternalError);
  9. HttpResponse::InternalServerError().json(resp)
  10. },
  11. NetworkError::BadRequest(ref resp) => HttpResponse::BadRequest().json(resp),
  12. NetworkError::Unauthorized => {
  13. let resp = FlowyResponse::from_msg("Unauthorized", ServerCode::Unauthorized);
  14. HttpResponse::Unauthorized().json(resp)
  15. },
  16. }
  17. }
  18. }
  19. impl<T: Serialize> std::convert::Into<HttpResponse> for FlowyResponse<T> {
  20. fn into(self) -> HttpResponse {
  21. match serde_json::to_string(&self) {
  22. Ok(body) => HttpResponse::Ok().body(Body::from(body)),
  23. Err(e) => {
  24. let msg = format!("Serial error: {:?}", e);
  25. NetworkError::InternalError(msg).error_response()
  26. },
  27. }
  28. }
  29. }