Skip to content

Commit

Permalink
Error handler on pastebin example
Browse files Browse the repository at this point in the history
  • Loading branch information
connorslade committed Dec 23, 2023
1 parent 8236698 commit f30e362
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 8 deletions.
4 changes: 2 additions & 2 deletions examples/basic/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ <h2>Routes</h2>
<ul>
<li><a href="/greet/World">Greet</a></li>
<li><a href="/ip">Your Ip</a></li>
<li><a href="/random">Random Number</a></li>
<li><a href="/analytics">Analytics</a></li>
<li><a href="/api/random">Random Number</a></li>
<li><a href="/api/analytics">Analytics</a></li>
</ul>
</body>
</html>
41 changes: 41 additions & 0 deletions examples/paste_bin/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use std::sync::Arc;

use afire::{headers::Vary, route::RouteError, Content, HeaderName, Request, Response, Server};
use serde_json::json;

use crate::app::App;

pub fn error_handler(_server: Arc<Server<App>>, req: Arc<Request>, error: RouteError) -> Response {
if req
.headers
.get(HeaderName::Accept)
.map(|x| x == "application/json")
.unwrap_or(false)
{
Response::new()
.text(json!({
"message": error.message,
"location": error.location.map(|x| x.to_string()),
"error": error.error.map(|x| format!("{x:?}")),
}))
.content(Content::JSON)
} else {
Response::new()
.text(format!(
"Internal Server Error\n{}{}{}",
error.message,
error
.error
.map(|x| format!("\n{:?}", x))
.unwrap_or_default(),
error
.location
.map(|x| format!("\n{}", x))
.unwrap_or_default(),
))
.content(Content::TXT)
}
.header(Vary::headers([HeaderName::Accept]))
.status(error.status)
.headers(error.headers)
}
2 changes: 2 additions & 0 deletions examples/paste_bin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use app::App;
mod app;
mod config;
mod database;
mod error;
mod pages;
mod routes;

Expand All @@ -18,6 +19,7 @@ fn main() -> Result<()> {

// Create a new server with values loaded from config.toml
let mut server = Server::new(&app.config.server.host, app.config.server.port)
.error_handler(error::error_handler)
.workers(app.config.server.workers)
.state(app);

Expand Down
7 changes: 5 additions & 2 deletions lib/proto/http/content_type.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Common MIME types for HTTP responses.

use crate::{headers::ContentType, Header};
use crate::{
headers::{Charset, ContentType},
Header,
};

use super::mime::{self, Mime};

Expand Down Expand Up @@ -51,6 +54,6 @@ impl Content<'_> {
impl From<Content<'_>> for Header {
// Convert Content to a Content-Type Header
fn from(x: Content<'_>) -> Self {
ContentType::new(x.as_type()).into()
ContentType::new(x.as_type()).charset(Charset::Utf8).into()
}
}
6 changes: 6 additions & 0 deletions lib/proto/http/headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,12 @@ mod content_type {
}
}

/// Sets the charset of the ContentType header.
pub fn charset(mut self, charset: impl Into<Charset>) -> Self {
self.charset = Some(charset.into());
self
}

content_type_shortcut![
(html, HTML),
(text, TEXT),
Expand Down
8 changes: 4 additions & 4 deletions lib/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub struct Server<State: 'static + Send + Sync = ()> {
pub ip: IpAddr,

/// The event loop used to handle incoming connections.
pub event_loop: Box<dyn EventLoop<State>>,
pub event_loop: Box<dyn EventLoop<State> + Send + Sync>,

/// Routes to handle.
pub routes: Vec<Route<State>>,
Expand All @@ -46,7 +46,7 @@ pub struct Server<State: 'static + Send + Sync = ()> {
pub state: Option<Arc<State>>,

/// Default response for internal server errors
pub error_handler: Box<dyn ErrorHandler<State>>,
pub error_handler: Box<dyn ErrorHandler<State> + Send + Sync>,

/// Headers automatically added to every response.
pub default_headers: Headers,
Expand Down Expand Up @@ -170,7 +170,7 @@ impl<State: Send + Sync> Server<State> {
/// The default is [`TcpEventLoop`], which uses the standard library's built-in TCP listener.
///
/// The [afire_tls](https://github.com/Basicprogrammer10/afire_tls) crate contains an event loop that uses rustls to handle TLS connections.
pub fn event_loop(self, event_loop: impl EventLoop<State> + 'static) -> Self {
pub fn event_loop(self, event_loop: impl EventLoop<State> + Send + Sync + 'static) -> Self {
Server {
event_loop: Box::new(event_loop),
..self
Expand Down Expand Up @@ -292,7 +292,7 @@ impl<State: Send + Sync> Server<State> {
/// .text(format!("Internal Server Error: {}", err.message))
/// }));
/// ```
pub fn error_handler(self, res: impl ErrorHandler<State> + 'static) -> Self {
pub fn error_handler(self, res: impl ErrorHandler<State> + Send + Sync + 'static) -> Self {
trace!("{}Setting Error Handler", emoji("✌"));

Self {
Expand Down

0 comments on commit f30e362

Please sign in to comment.