Skip to content
Snippets Groups Projects
Commit 99a4f735 authored by nutzer05's avatar nutzer05
Browse files

Add error correction

parent cd4407ec
No related branches found
No related tags found
No related merge requests found
......@@ -13,33 +13,39 @@ enum CalcOp {
#[derive(Deserialize)]
struct CalcReq {
a: f32,
b: f32,
a: i32,
b: i32,
op: CalcOp,
}
#[derive(Serialize)]
struct CalcRes {
res: f32,
res: i32,
}
impl CalcReq {
fn calc(&self) -> CalcRes {
fn calc(&self) -> Option<CalcRes> {
let res = match self.op {
CalcOp::Add => self.a + self.b,
CalcOp::Sub => self.a - self.b,
CalcOp::Mul => self.a * self.b,
CalcOp::Div => self.a / self.b,
CalcOp::Add => self.a.checked_add(self.b)?,
CalcOp::Sub => self.a.checked_sub(self.b)?,
CalcOp::Mul => self.a.checked_mul(self.b)?,
CalcOp::Div => self.a.checked_div(self.b)?,
};
CalcRes { res }
Some(CalcRes { res })
}
}
#[post("/calc")]
async fn calc(req_body: String) -> impl Responder {
let req: CalcReq = serde_json::from_str(&req_body).unwrap();
let res = req.calc();
let req: CalcReq = match serde_json::from_str(&req_body) {
Ok(r) => r,
Err(e) => return HttpResponse::BadRequest().body(e.to_string())
};
let res = match req.calc() {
Some(r) => r,
None => return HttpResponse::BadRequest().body("Arithmetic error")
};
HttpResponse::Ok().body(serde_json::to_string(&res).unwrap())
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment