エラーとログ
ハンドラは応答を持つエラーを返して失敗し、ページはその応答のステータスと文言を表示します。訪問者に見せないことは、tracing でサーバーのログに書きます。
エラー
ハンドラは、E が axum の IntoResponse を実装する Result<_, E> を返せるので、? が使えます。アクションでは差分のそうした Result に IntoActionResponse が実装されていて、ページでは PageResponse が同じようにエラーで応答します。応答はエラーの応答そのものです。下の NotesFull は、訪問者が読む 1 文を付けて 409 Conflict で応答します。
use axum::Router;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use hypersig::html::{button, p};
use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Notes {
count: i32,
problem: String,
}
struct NotesFull;
impl IntoResponse for NotesFull {
fn into_response(self) -> Response {
(StatusCode::CONFLICT, "You can keep 3 notes.").into_response()
}
}
fn add_one(count: i32) -> Result<i32, NotesFull> {
(count < 3).then_some(count + 1).ok_or(NotesFull)
}
hypersig::routes! {
fn pages(Router<()>);
action ADD: Action<Notes, i32> = post "/notes" => add;
}
async fn add((): (), count: i32) -> Result<Patches<Notes>, NotesFull> {
let count = add_one(count)?;
Ok(Notes::count().patch(count).into())
}
// The page shows the status and the body of a failed call.
let call = ADD.call_with(Notes::count()).error(Notes::problem());
let _add = button().on_click(call).text("Add");
let _problem = p().bind_text(Notes::problem());
let _app: Router = pages(Router::new());IntoResponse のないエラーの型では、ルーターが送る応答がないので、routes! がコンパイルできません。
use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Notes {
count: i32,
}
// No `IntoResponse`: the router has no answer to send for it.
struct NotesFull;
// error[E0277]: `Result<Patches<Notes>, NotesFull>` is not a reply of an action on the page whose signals are `Notes`
hypersig::routes! {
fn pages(Router<()>);
action ADD: Action<Notes, i32> = post "/notes" => add;
}
async fn add((): (), count: i32) -> Result<Patches<Notes>, NotesFull> {
let count = (count < 3).then_some(count + 1).ok_or(NotesFull)?;
Ok(Notes::count().patch(count).into())
}ページに出るもの
応答のステータスが 2xx 以外のアクションは、ページでは失敗になります。ランタイムは Call::error に渡したシグナルにメッセージを、Call::status に渡したシグナルにステータスを書きます。どちらも呼び出しを送るときに "" と 0 に戻ります。メッセージは応答によって次のように決まります。
| 応答 | error のシグナル | status のシグナル |
|---|---|---|
2xx 以外で、本文が text/plain(axum は String と &str をこの形式で送ります) | 本文。たとえば You can keep 3 notes. | ステータス。たとえば 409 |
| 2xx 以外で、本文が空か、プロキシの HTML のエラーページのようにほかの形式 | ステータスとその理由。たとえば 502 Bad Gateway | ステータス |
| 2xx だが、リダイレクトされたか、ルーターの応答でないか、ルーターが応答を終える前に閉じた | ランタイム自身のメッセージ | 0 |
| 応答がない。たとえば接続が切れた | ブラウザのメッセージ | 0 |
失敗はどれもブラウザのコンソールにも書かれます。上のサンプルの呼び出しが失敗すると、次の行が出ます。
hypersig: POST /notes failed with 409: You can keep 3 notes.これらのシグナルをページに出す方法と、失敗したときに文を実行する方法は 呼び出し中と失敗 で説明します。
パニックするハンドラ
アクション、ストリーム、アップロードのハンドラが値を返す前にパニックすると、500 Internal Server Error で応答します。ページはこれをほかの失敗した呼び出しと同じように表示し、既定のパニックフックはメッセージを標準エラー出力に書きます。ストリームのハンドラが返したストリームは応答が始まってから読まれるので、読んでいるあいだのパニックは応答が終わる前に接続を閉じ、ページにはステータス 0 が届きます。ページのハンドラや、描画中のページがパニックしたときは、本文が空の 500 Internal Server Error で応答します。
拒否をログに書く
ハンドラが動く前にルーターが拒否するリクエストには、RequestError で応答します。拒否するリクエストの一覧は エクストラクタとヘッダー にあります。ストリーミングのアップロードのハンドラは、読んでいるあいだに本文がおかしくなるとこれを受け取り、? で返します。そのメソッドからは、訪問者に見せる本文より多くの情報をログのために取り出せます。
| 項目 | 内容 |
|---|---|
status() | 応答のステータス。たとえば 413 |
Display | 拒否ごとに決まった 1 文。応答の本文にもなります |
source() | 形の崩れた本文や引数についてのパーサーのメッセージ。引数の型のフィールド名と訪問者の入力を含みます |
backtrace() | エラーを作った場所のバックトレース。RUST_BACKTRACE で求めたときに記録されます |
ログ
このサイトのサンプルは短く保つためにエラーのサーバー側の内容を eprintln! で書いています。アプリケーションでは tracing でログを書きます。ハンドラは tracing::warn! や tracing::error! でイベントを書き、tracing-subscriber がイベントを標準エラー出力に書きます。tower-http の TraceLayer を layer でルーターに付けると、リクエストごとに、応答のステータスとかかった時間を書いた行が加わります。Cargo.toml に 3 つのクレートを追加してください。
[dependencies]
tower-http = { version = "0.7", features = ["trace"] }
tracing = "0.1"
tracing-subscriber = "0.3"use axum::Router;
use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer};
use tracing::Level;
hypersig::routes! {
fn pages(Router<()>);
action SAVE: Action<Profile, String> = post "/save" => save;
}
async fn save((): (), name: String) -> Result<Patches<Profile>, (StatusCode, &'static str)> {
if name.is_empty() {
// An event of the application's own, at the level it picks.
tracing::warn!("refused an empty name");
return Err((StatusCode::UNPROCESSABLE_ENTITY, "Write a name."));
}
Ok(Profile::saved().patch(name).into())
}
// Once, at the start of `main`: write each event at INFO or above to stderr.
tracing_subscriber::fmt().with_max_level(Level::INFO).init();
// Each request gets a span with its method and URI, and one line with the
// answer's status and how long it took. Both are DEBUG unless set here.
let trace = TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
.on_response(DefaultOnResponse::new().level(Level::INFO));
let _app: Router = pages(Router::new()).layer(trace);コンパイラが検査しないこと
コンパイラが検査するのは、エラーに応答があることで、応答の中身ではありません。失敗したアクションの text/plain の本文はそのまま訪問者に見えるので、本文には訪問者が次にどうすればよいかを書いてください。クエリやファイルのパスを含みうるエラー自身のメッセージは、サーバーのログに書きます。
IntoResponse が書いたもの、たとえば 1 行のテキストで応答し、サイトのページでは応答しません。404 にページを出す方法は エラーページ で説明します。次の アップロード では呼び出しでファイルを送ります。