コマンドのエラー出力を取得する

Recipe ID: shell-004

コマンド実行時のエラーメッセージ(標準エラー出力)を取得する方法を解説します。
終了コード (code) が 0 以外の場合に出力されることが多いですが、進捗情報などを stderr に出力するツールもあります。

前提条件

プラグインのインストールが必要です。

npm run tauri add shell

Permissions (権限) の設定

src-tauri/capabilities/default.json に以下の権限を追加します。

{
  "permissions": [
    ...,
    "shell:allow-open",
    {
      "identifier": "shell:allow-execute",
      "allow": [
        {
          "name": "cat",
          "cmd": "cat",
          "args": true
        }
      ]
    }
  ]
}

1. フロントエンドから作成する (TypeScript)

execute() の戻り値オブジェクトの stderr プロパティを参照します。

エラー出力の確認

import { Command } from '@tauri-apps/plugin-shell';

async function runAndCheckError() {
  // 存在しないファイルを表示しようとしてエラーを起こす例
  const cmd = Command.create('cat', ['non-existent-file.txt']);
  
  const output = await cmd.execute();
  
  if (output.code !== 0) {
    console.warn(`Command failed with code: ${output.code}`);
    console.warn(`STDERR: ${output.stderr}`);
  } else {
    console.log(`Success: ${output.stdout}`);
  }
}

2. バックエンドから作成する (Rust)

Command::output() の戻り値に含まれる .status.stderr を確認します。

use std::process::Command;

#[tauri::command]
fn check_error_output() {
    let output = Command::new("cat")
        .arg("non-existent-file.txt")
        .output()
        .expect("failed to execute process");

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        println!("Error Code: {:?}", output.status.code());
        println!("STDERR: {}", stderr);
    } else {
        let stdout = String::from_utf8_lossy(&output.stdout);
        println!("Success: {}", stdout);
    }
}

※ Security の permissionscat コマンドが許可されている必要があります。