できない.dev

例外の原因を残したまま包み直すには

低レベルの例外を、業務の意味を持つ例外に包み直しても、元の原因をたどれるように残す書き方を各言語で示す。
原因を渡し忘れると何が消えるかと、ログで原因の連鎖がどう見えるかまでを扱う。

公開:

選んだ言語は、ほかのサンプルコードを開いたときも最初に表示する。

Python

class ConfigError(Exception):
    pass
 
 
def load_config(path):
    try:
        with open(path, encoding="utf-8") as f:
            return f.read()
    except OSError as e:
        # from e を付けると、元の例外が __cause__ に残る
        raise ConfigError(f"設定を読めない: {path}") from e
 
 
try:
    load_config("missing.json")
except ConfigError as e:
    print(e)  # -> 設定を読めない: missing.json
    print(repr(e.__cause__))  # -> FileNotFoundError(2, 'No such file or directory')
    print(isinstance(e.__cause__, FileNotFoundError))  # -> True
 
 
# from を付けない場合は __cause__ が None で、__context__ に暗黙で入る
def without_from():
    try:
        open("missing.json", encoding="utf-8")
    except OSError:
        raise ConfigError("設定を読めない")
 
 
try:
    without_from()
except ConfigError as e:
    print(e.__cause__)  # -> None
    print(type(e.__context__).__name__)  # -> FileNotFoundError

raise ... from e と書くと、元の例外が新しい例外の __cause__ に残る。
from を付けずに except の中で別の例外を投げても __context__ には入るが、__cause__ は None のままで、原因として明示したことにはならない。

JavaScript

import { readFileSync } from "node:fs";
 
class ConfigError extends Error {
  constructor(message, options) {
    super(message, options); // options に { cause } を渡すと error.cause に残る
    this.name = "ConfigError";
  }
}
 
function loadConfig(path) {
  try {
    return readFileSync(path, "utf8");
  } catch (e) {
    throw new ConfigError(`設定を読めない: ${path}`, { cause: e });
  }
}
 
try {
  loadConfig("missing.json");
} catch (e) {
  console.log(e.message); // -> 設定を読めない: missing.json
  console.log(e.cause.code); // -> ENOENT
  console.log(e.cause instanceof Error); // -> true
}
 
// cause を渡さないと、元のエラーは消える
try {
  try {
    readFileSync("missing.json", "utf8");
  } catch {
    throw new ConfigError("設定を読めない");
  }
} catch (e) {
  console.log(e.cause); // -> undefined
}

new Error(message, { cause }) の第 2 引数に元のエラーを渡すと、error.cause から取り出せる。
Error を継承したクラスでも、コンストラクターで super(message, options) と引数を渡し切らないと cause は消える。

TypeScript

import { readFileSync } from "node:fs";
 
class ConfigError extends Error {
  constructor(message: string, options?: ErrorOptions) {
    super(message, options); // ErrorOptions は lib に es2022 以上が必要
    this.name = "ConfigError";
  }
}
 
function loadConfig(path: string): string {
  try {
    return readFileSync(path, "utf8");
  } catch (e) {
    throw new ConfigError(`設定を読めない: ${path}`, { cause: e });
  }
}
 
try {
  loadConfig("missing.json");
} catch (e) {
  if (e instanceof ConfigError) {
    console.log(e.message); // -> 設定を読めない: missing.json
    // cause の型は unknown なので、使う前に絞り込む
    if (e.cause instanceof Error && "code" in e.cause) {
      console.log(e.cause.code); // -> ENOENT
    }
  }
}

cause を受け取る側は、ErrorOptions を引数に取って super へ渡す。
cause の型は unknown なので、instanceof で絞り込んでから code などを読む。
ErrorOptions は lib に es2022 以上を入れた設定で使える。

できないときTypeScript「Cannot find name 'process'」の原因と直し方

Go

package main
 
import (
	"errors"
	"fmt"
	"io/fs"
	"os"
)
 
func loadConfig(path string) ([]byte, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		// %w で包むと、元のエラーが Unwrap でたどれる
		return nil, fmt.Errorf("設定を読めない: %s: %w", path, err)
	}
	return data, nil
}
 
func main() {
	_, err := loadConfig("missing.json")
	fmt.Println(err)                            // -> 設定を読めない: missing.json: open missing.json: no such file or directory
	fmt.Println(errors.Is(err, os.ErrNotExist)) // -> true
	fmt.Println(errors.Unwrap(err))             // -> open missing.json: no such file or directory
 
	var pe *fs.PathError
	if errors.As(err, &pe) {
		fmt.Println(pe.Op, pe.Path) // -> open missing.json
	}
 
	// %v で書くと文字列になるだけで、元のエラーは失われる
	_, err2 := os.ReadFile("missing.json")
	flat := fmt.Errorf("設定を読めない: %v", err2)
	fmt.Println(errors.Is(flat, os.ErrNotExist)) // -> false
	fmt.Println(errors.Unwrap(flat) == nil)      // -> true
}

fmt.Errorf の %w で包むと、errors.Is と errors.As が元のエラーまでたどれる。
%v で書いた場合は文字列になるだけで、errors.Unwrap は nil を返す。

Rust

use std::error::Error;
use std::fmt;
use std::fs;
 
#[derive(Debug)]
struct ConfigError {
    path: String,
    source: std::io::Error, // 元のエラーを持たせる
}
 
impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "設定を読めない: {}", self.path)
    }
}
 
impl Error for ConfigError {
    // source を返すと、呼び出し側が原因をたどれる
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.source)
    }
}
 
fn load_config(path: &str) -> Result<String, ConfigError> {
    fs::read_to_string(path).map_err(|e| ConfigError {
        path: path.to_string(),
        source: e,
    })
}
 
fn main() {
    let err = load_config("missing.json").unwrap_err();
    println!("{}", err); // -> 設定を読めない: missing.json
    let mut cause = err.source();
    while let Some(c) = cause {
        println!("原因: {}", c); // -> 原因: No such file or directory (os error 2)
        cause = c.source();
    }
}

標準ライブラリだけで包むには、元のエラーをフィールドに持たせ、Error トレイトの source でそれを返す。
呼び出し側は source を繰り返し呼べば、原因を外側から内側へたどれる。

Java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
 
public class Main {
    static class ConfigException extends Exception {
        ConfigException(String message, Throwable cause) {
            super(message, cause); // 第 2 引数が getCause() で返る
        }
    }
 
    static String loadConfig(String path) throws ConfigException {
        try {
            return Files.readString(Path.of(path));
        } catch (IOException e) {
            throw new ConfigException("設定を読めない: " + path, e);
        }
    }
 
    public static void main(String[] args) {
        try {
            loadConfig("missing.json");
        } catch (ConfigException e) {
            System.out.println(e.getMessage()); // -> 設定を読めない: missing.json
            System.out.println(e.getCause()); // -> java.nio.file.NoSuchFileException: missing.json
            System.out.println(e.getCause() instanceof java.nio.file.NoSuchFileException); // -> true
        }
 
        // cause を渡さずに投げ直すと、getCause() は null になる
        try {
            try {
                Files.readString(Path.of("missing.json"));
            } catch (IOException e) {
                throw new RuntimeException("設定を読めない");
            }
        } catch (RuntimeException e) {
            System.out.println(e.getCause()); // -> null
        }
    }
}

例外のコンストラクターの第 2 引数に元の例外を渡すと、getCause で取り出せる。
チェック例外を RuntimeException に包み直すときも、原因を渡さないと元のスタックトレースが失われる。

C#

try
{
    LoadConfig("missing.json");
}
catch (ConfigException e)
{
    Console.WriteLine(e.Message); // -> 設定を読めない: missing.json
    Console.WriteLine(e.InnerException!.GetType().Name); // -> FileNotFoundException
}
 
// cause を渡さずに投げ直すと、InnerException は null になる
try
{
    try
    {
        File.ReadAllText("missing.json");
    }
    catch (IOException)
    {
        throw new ConfigException("設定を読めない");
    }
}
catch (ConfigException e)
{
    Console.WriteLine(e.InnerException == null); // -> True
}
 
static string LoadConfig(string path)
{
    try
    {
        return File.ReadAllText(path);
    }
    catch (IOException e)
    {
        throw new ConfigException($"設定を読めない: {path}", e);
    }
}
 
class ConfigException : Exception
{
    public ConfigException(string message) : base(message) { }
 
    // 第 2 引数の innerException が InnerException プロパティに残る
    public ConfigException(string message, Exception inner) : base(message, inner) { }
}

例外クラスのコンストラクターで base(message, inner) を呼ぶと、元の例外が InnerException に残る。
throw new で別の例外を投げるときに inner を渡し忘れると、InnerException は null になる。

つまずき

包み直すときに元の例外を渡さないと、原因の情報が消える。
上のコードの後半はその例で、JavaScript の cause は undefined、Java の getCause() は null、C# の InnerException は null になる。
ログに「設定を読めない」としか残らず、ファイルが無いのか権限が無いのかが分からなくなる。
包み直す箇所では、元の例外を渡す引数を必ず使う。

Python は from の有無で __cause__ と __context__ が分かれる

except の中で別の例外を投げると、元の例外は自動で __context__ に入る。
raise ... from e と書いたときだけ __cause__ にも入り、「この例外が原因で起きた」という意味になる。
上の実行例では、from を付けた場合に e.__cause__ が FileNotFoundError になり、付けない場合は None になった。
原因を見せたくないときは from None と書くと、連鎖の表示ごと消せる。

Go は %w で包まないと errors.Is が効かない

fmt.Errorf で %v を使うと、元のエラーの文言が文字列として入るだけになる。
上の実行例では、%w で包んだ場合は errors.Is(err, os.ErrNotExist) が true になり、%v で書いた場合は false になった。
エラーの種類で処理を分けたいなら、包むときは %w を使う。

ログには原因の連鎖まで出す

包んだ例外をそのまま出力すると、言語によって原因の表示が違う。
Python の traceback.print_exc() は The above exception was the direct cause of the following exception: という行で 2 つの例外をつなぐ。
Java の printStackTrace は Caused by: の行に原因を出す。
Node.js で console.log(error) とすると、[cause]: の下に元のエラーが入れ子で出る。
Rust は Display で外側の文言しか出ないため、上のコードのように source を繰り返し呼んで原因を出す。