アプリケーション内で予期せぬエラーや、ユーザーが解決すべき問題が発生した際に、適切な警告(エラー)ダイアログを表示する方法を紹介します。
前提条件
プラグインの追加
ダイアログ機能を利用するには dialog プラグインが必要です。
npm run tauri add dialog
src-tauri/src/lib.rs に .plugin(tauri_plugin_dialog::init()) が追加されていることを確認してください。
Permissions (権限) の設定
src-tauri/capabilities/default.json に dialog:allow-message 権限を追加します。
{
"permissions": [
...,
"dialog:default",
"dialog:allow-message"
]
}
1. フロントエンドから作成する (TypeScript)
message() 関数で kind: 'error' または 'warning' を指定します。
シンプルなエラー表示
ユーザーにエラー内容を伝える最も単純な方法です。
import { message } from '@tauri-apps/plugin-dialog';
try {
// エラーが発生する可能性のある処理
throw new Error("ファイルの読み込みに失敗しました。");
} catch (e) {
await message(`${e}`, {
title: 'エラー',
kind: 'error'
});
}
ユーザーの操作ミスに対する警告
エラーだけでなく、ユーザーに注意を促す場合にも使用できます。
import { message } from '@tauri-apps/plugin-dialog';
const input = ""; // ユーザー入力など
if (input.trim() === "") {
await message('入力欄が空です。\n必須項目を入力してください。', {
title: '入力エラー',
kind: 'warning', // 警告アイコンになります
okLabel: '修正する'
});
}
Rust コマンドからのエラーをキャッチして表示する
Rust 側(バックエンド)で発生したエラーをフロントエンドで受け取り、ダイアログ表示するパターンです。
import { invoke } from '@tauri-apps/api/core';
import { message } from '@tauri-apps/plugin-dialog';
// Rustコマンドの呼び出し
invoke('my_custom_command')
.then((response) => {
// 成功時の処理
console.log(response);
})
.catch(async (error) => {
// 失敗(エラー)時はダイアログを表示
await message(`コマンド実行中にエラーが発生しました:\n${error}`, {
title: '実行時エラー',
kind: 'error',
});
});
2. バックエンドから作成する (Rust)
Rust 側でエラーが発生した際に直接ダイアログを出すことも可能です。
use tauri_plugin_dialog::{DialogExt, MessageDialogKind};
// 例:コマンド内でエラー時に表示
#[tauri::command]
fn do_something(app: tauri::AppHandle) {
if let Err(e) = some_risky_operation() {
app.dialog()
.message(format!("エラーが発生しました: {}", e))
.kind(MessageDialogKind::Error)
.title("Server Error")
.show(|_| {});
}
}
fn some_risky_operation() -> Result<(), String> {
Err("Connection Failed".into())
}
補足
- UIスレッド: ダイアログはメインスレッド(UIスレッド)で表示される必要がありますが、Tauri の API がこれをハンドルしてくれます。