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, Result};use tera::Tera;// Custom error handlers, to return HTML responses when an error occurs.pub 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 tera = request.app_data::<web::Data<Tera>>().map(|t| t.get_ref());match tera {Some(tera) => {let mut context = tera::Context::new();context.insert("error", error);context.insert("status_code", res.status().as_str());let body = tera.render("error.html", &context);match body {Ok(body) => Response::build(res.status()).content_type("text/html").body(body),Err(_) => fallback(error),}}None => fallback(error),}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。