Skip to content

Commit

Permalink
feat: respond with error page when having errors
Browse files Browse the repository at this point in the history
  • Loading branch information
lomirus committed Dec 18, 2023
1 parent 6e7315c commit 1f7f4fb
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/server.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::{collections::HashMap, io::ErrorKind};

use async_std::{fs, path::PathBuf, prelude::*, sync::Mutex};
use tide::{listener::Listener, Body, Request, Response, StatusCode};
Expand Down Expand Up @@ -103,12 +103,27 @@ async fn static_assets(
path.push("index.html");
}
let mime = mime_guess::from_path(&path).first_or_text_plain();
let mut response = Response::new(StatusCode::InternalServerError);
response.set_content_type(mime.to_string().as_str());

// Read the file.
let mut file = match fs::read(&path).await {
Ok(file) => file,
Err(err) => {
log::warn!("{}", err);
if mime == "text/html" {
let script = format!(include_str!("templates/websocket.html"), host, port);
let html = format!(
include_str!("templates/error.html"),
script,
err.to_string()
);
response.set_body(Body::from_string(html));
if err.kind() == ErrorKind::NotFound {
response.set_status(StatusCode::NotFound);
}
return Ok(response);
}
return Err(tide::Error::new(StatusCode::NotFound, err));
}
};
Expand All @@ -125,8 +140,7 @@ async fn static_assets(
let script = format!(include_str!("templates/websocket.html"), host, port);
file = format!("{text}{script}").into_bytes();
}
let mut response: Response = Body::from_bytes(file).into();
response.set_content_type(mime.to_string().as_str());
response.set_body(Body::from_bytes(file));

Ok(response)
}
8 changes: 8 additions & 0 deletions src/templates/error.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html>
<head>
<title>Live Server Error</title>
{}
</head>
<body>{}</body>
</html>

0 comments on commit 1f7f4fb

Please sign in to comment.