add error handlers

This commit is contained in:
cel 🌸 2023-01-16 05:49:03 +00:00
parent 859f9fe9f8
commit 67790fcb2f
Signed by: cel
GPG Key ID: 48E29AF13B5F1349
2 changed files with 41 additions and 4 deletions

View File

@ -1,6 +1,8 @@
use listenbrainz::raw::response::UserPlayingNowResponse; use listenbrainz::raw::response::UserPlayingNowResponse;
use rocket::fs::{relative, FileServer}; use rocket::fs::{relative, FileServer};
use rocket::http::Status;
use rocket::response::Responder; use rocket::response::Responder;
use rocket::Request;
use rocket_dyn_templates::{context, Template}; use rocket_dyn_templates::{context, Template};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -55,10 +57,6 @@ impl ScrobbleData {
async fn home() -> Template { async fn home() -> Template {
let listenbrainz = listenbrainz::raw::Client::new(); let listenbrainz = listenbrainz::raw::Client::new();
let playingnow = listenbrainz.user_playing_now("celblossom").unwrap(); let playingnow = listenbrainz.user_playing_now("celblossom").unwrap();
println!(
"{}",
playingnow.payload.listens[0].track_metadata.artist_name
);
let listenbrainz_data = ScrobbleData::new(playingnow); let listenbrainz_data = ScrobbleData::new(playingnow);
println!("{}", listenbrainz_data.is_scrobbling); println!("{}", listenbrainz_data.is_scrobbling);
@ -79,11 +77,40 @@ async fn contact() -> Template {
// posts // posts
// } // }
#[catch(404)]
fn not_found(req: &Request) -> Template {
let message = "i either haven't built this page yet or it looks like you're a little lost";
Template::render(
"error",
context! { status: "404", req: req.uri(), message: message },
)
}
#[catch(501)]
fn server_error(req: &Request) -> Template {
let message = "it looks like this is not yet here!!!";
Template::render(
"error",
context! { status: "501", req: req.uri(), message: message },
)
}
#[catch(default)]
fn error(status: Status, req: &Request) -> Template {
let status = format!("{}", status);
let message = "there was an error";
Template::render(
"error",
context! { status: status, req: req.uri(), message: message },
)
}
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), rocket::Error> { async fn main() -> Result<(), rocket::Error> {
let _rocket = rocket::build() let _rocket = rocket::build()
.attach(Template::fairing()) .attach(Template::fairing())
.mount("/", routes![home, contact]) .mount("/", routes![home, contact])
.register("/", catchers![not_found, server_error, error])
.mount("/", FileServer::from(relative!("static"))) .mount("/", FileServer::from(relative!("static")))
.launch() .launch()
.await?; .await?;

10
templates/error.html.tera Normal file
View File

@ -0,0 +1,10 @@
{% extends "base" %}
{% block content %}
<div class="content panel">
<h2>Error {{ status }}: {{ req }}</h2>
<h3>{{ message }}</h3>
</div>
{% endblock %}