错误

Actix使用自己的actix_web::error::Error类型和 actix_web::error::ResponseError特征来处理Web处理程序的错误。

如果处理程序返回一个Error(指一般的Rust特征 std::error::Error)Result也实现了 ResponseError特征,actix会将该错误呈现为HTTP响应。 ResponseError有一个名为return的函数error_response()返回HttpResponse

  1. pub trait ResponseError: Fail {
  2. fn error_response(&self) -> HttpResponse {
  3. HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
  4. }
  5. }

一个Responder强制将兼容Result转换的HTTP响应:

  1. impl<T: Responder, E: Into<Error>> Responder for Result<T, E>

Error在上面的代码中是actix的错误定义,并且实现的任何错误ResponseError都可以自动转换为一个。

Actix-web提供ResponseError一些常见的非actix错误的实现。例如,如果处理程序以a响应io::Error,则该错误将转换为HttpInternalServerError

  1. use std::io;
  2. fn index(req: &HttpRequest) -> io::Result<fs::NamedFile> {
  3. Ok(fs::NamedFile::open("static/index.html")?)
  4. }

有关外部实现的完整列表,请参阅actix-web API文档ResponseError

自定义错误响应的示例

以下是一个示例实现 ResponseError:

  1. use actix_web::*;
  2. #[derive(Fail, Debug)]
  3. #[fail(display="my error")]
  4. struct MyError {
  5. name: &'static str
  6. }
  7. // Use default implementation for `error_response()` method
  8. impl error::ResponseError for MyError {}
  9. fn index(req: &HttpRequest) -> Result<&'static str, MyError> {
  10. Err(MyError{name: "test"})
  11. }

ResponseError 有一个默认的实现error_response(),它将呈现500(内部服务器错误),这就是index上面执行处理程序时会发生的事情 。

覆盖error_response()以产生更有用的结果:

  1. #[macro_use] extern crate failure;
  2. use actix_web::{App, HttpRequest, HttpResponse, http, error};
  3. #[derive(Fail, Debug)]
  4. enum MyError {
  5. #[fail(display="internal error")]
  6. InternalError,
  7. #[fail(display="bad request")]
  8. BadClientData,
  9. #[fail(display="timeout")]
  10. Timeout,
  11. }
  12. impl error::ResponseError for MyError {
  13. fn error_response(&self) -> HttpResponse {
  14. match *self {
  15. MyError::InternalError => HttpResponse::new(
  16. http::StatusCode::INTERNAL_SERVER_ERROR),
  17. MyError::BadClientData => HttpResponse::new(
  18. http::StatusCode::BAD_REQUEST),
  19. MyError::Timeout => HttpResponse::new(
  20. http::StatusCode::GATEWAY_TIMEOUT),
  21. }
  22. }
  23. }
  24. fn index(req: &HttpRequest) -> Result<&'static str, MyError> {
  25. Err(MyError::BadClientData)
  26. }

Error helpers

Actix提供了一组错误辅助函数,可用于从其他错误生成特定的HTTP错误代码。在这里,我们使用以下方法将MyError未实现ResponseError特征的转换为400(错误请求) map_err

  1. # extern crate actix_web;
  2. use actix_web::*;
  3. #[derive(Debug)]
  4. struct MyError {
  5. name: &'static str
  6. }
  7. fn index(req: &HttpRequest) -> Result<&'static str> {
  8. let result: Result<&'static str, MyError> = Err(MyError{name: "test"});
  9. Ok(result.map_err(|e| error::ErrorBadRequest(e.name))?)
  10. }

有关可用错误帮助程序的完整列表,请参阅actix-web error模块的API文档。

与failure的兼容性

Actix-web提供与failure库的自动兼容性,以便将错误派生fail自动转换为actix错误。请记住,这些错误将使用默认的500状态代码呈现,除非您还error_response()为它们提供自己的实现。

Error logging

Actix在WARN日志级别记录所有错误。如果应用程序的日志级别设置为DEBUG并RUST_BACKTRACE启用,则还会记录回溯。这些可以配置环境变量:

  1. >> RUST_BACKTRACE=1 RUST_LOG=actix_web=debug cargo run

Error类型使用cause的错误回溯(如果可用)。如果基础故障不提供回溯,则构造新的回溯指向转换发生的点(而不是错误的起源)。

错误处理的推荐做法

考虑将应用程序产生的错误划分为两大类可能是有用的:那些旨在面向用户的错误和那些不是面向用户的错误。

前者的一个例子是我可能会使用failure来指定一个UserError 枚举ValidationError以便在用户发送错误输入时返回:

  1. #[macro_use] extern crate failure;
  2. use actix_web::{HttpResponse, http, error};
  3. #[derive(Fail, Debug)]
  4. enum UserError {
  5. #[fail(display="Validation error on field: {}", field)]
  6. ValidationError {
  7. field: String,
  8. }
  9. }
  10. impl error::ResponseError for UserError {
  11. fn error_response(&self) -> HttpResponse {
  12. match *self {
  13. UserError::ValidationError { .. } => HttpResponse::new(
  14. http::StatusCode::BAD_REQUEST),
  15. }
  16. }
  17. }

这将完全按预期运行,因为定义的错误消息 display是用明确的意图写入的,用户可以读取。

但是,发送错误消息对于所有错误都是不可取的 - 在服务器环境中发生许多故障,我们可能希望从用户隐藏这些特定信息。例如,如果数据库出现故障并且客户端库开始产生连接超时错误,或者HTML模板格式不正确以及呈现时出错。在这些情况下,可能最好将错误映射到适合用户使用的一般错误。

这是一个InternalError 使用自定义消息将内部错误映射到面向用户的示例:

  1. #[macro_use] extern crate failure;
  2. use actix_web::{App, HttpRequest, HttpResponse, http, error, fs};
  3. #[derive(Fail, Debug)]
  4. enum UserError {
  5. #[fail(display="An internal error occurred. Please try again later.")]
  6. InternalError,
  7. }
  8. impl error::ResponseError for UserError {
  9. fn error_response(&self) -> HttpResponse {
  10. match *self {
  11. UserError::InternalError => HttpResponse::new(
  12. http::StatusCode::INTERNAL_SERVER_ERROR),
  13. }
  14. }
  15. }
  16. fn index(_: &HttpRequest) -> Result<&'static str, UserError> {
  17. fs::NamedFile::open("static/index.html").map_err(|_e| UserError::InternalError)?;
  18. Ok("success!")
  19. }

通过将错误划分为面向用户和非面向错误的错误,我们可以确保我们不会意外地将用户暴露给他们不应该看到的应用程序内部错误。