1
0
mirror of https://github.com/actix/examples synced 2025-06-28 18:00:37 +02:00

Demonstrate how to render error pages using templates.

This commit is contained in:
Pieter Frenssen
2020-05-19 18:21:39 +03:00
parent bc6f614f78
commit 986614d698
8 changed files with 128 additions and 4 deletions

View File

@ -5,7 +5,8 @@ authors = ["Alexandru Tiniuc <tiniuc.alexandru@gmail.com>"]
edition = "2018"
[dependencies]
actix-web = "2.0.0"
actix-http = "1.0.1"
actix-rt = "1.0.0"
actix-web = "2.0.0"
handlebars = { version = "3.0.0", features = ["dir_source"] }
serde_json = "1.0"

View File

@ -5,3 +5,4 @@ This is an example of how to use Actix Web with the [Handlebars templating langu
- http://localhost:8080
- http://localhost:8080/Emma/documents
- http://localhost:8080/Bob/passwords
- http://localhost:8080/some-non-existing-page - 404 error rendered using template

View File

@ -4,8 +4,11 @@ extern crate actix_web;
#[macro_use]
extern crate serde_json;
use actix_web::web;
use actix_web::{App, HttpResponse, HttpServer};
use actix_http::{body::Body, Response};
use actix_web::dev::ServiceResponse;
use actix_web::http::StatusCode;
use actix_web::middleware::errhandlers::{ErrorHandlerResponse, ErrorHandlers};
use actix_web::{web, App, HttpResponse, HttpServer, Result};
use handlebars::Handlebars;
@ -49,6 +52,7 @@ async fn main() -> io::Result<()> {
HttpServer::new(move || {
App::new()
.wrap(error_handlers())
.app_data(handlebars_ref.clone())
.service(index)
.service(user)
@ -57,3 +61,50 @@ async fn main() -> io::Result<()> {
.run()
.await
}
// Custom error handlers, to return HTML responses when an error occurs.
fn error_handlers() -> ErrorHandlers<Body> {
ErrorHandlers::new().handler(StatusCode::NOT_FOUND, not_found)
}
// Error handler for a 404 Page not found error.
fn not_found<B>(res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
let response = get_error_response(&res, "Page not found");
Ok(ErrorHandlerResponse::Response(
res.into_response(response.into_body()),
))
}
// Generic error handler.
fn get_error_response<B>(res: &ServiceResponse<B>, error: &str) -> Response<Body> {
let request = res.request();
// Provide a fallback to a simple plain text response in case an error occurs during the
// rendering of the error page.
let fallback = |e: &str| {
Response::build(res.status())
.content_type("text/plain")
.body(e.to_string())
};
let hb = request
.app_data::<web::Data<Handlebars>>()
.map(|t| t.get_ref());
match hb {
Some(hb) => {
let data = json!({
"error": error,
"status_code": res.status().as_str()
});
let body = hb.render("error", &data);
match body {
Ok(body) => Response::build(res.status())
.content_type("text/html")
.body(body),
Err(_) => fallback(error),
}
}
None => fallback(error),
}
}

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{{error}}</title>
</head>
<body>
<h1>{{status_code}} {{error}}</h1>
</body>
</html>