d附加额外函数的异常

原文

#!/usr/bin/env rdmd
import std;

auto contextWithString(T)(lazy scope T expression, string s)
{
    try
    {
        return expression();
    }
    catch (Exception e)
    {
        throw new Exception("%s\n%s".format(s, e.msg));
    }
    assert(false);
}

auto contextWithException(T)(lazy scope T expression, Exception delegate(Exception) handler)
{
    Exception newException;
    try
    {
        return expression();
    }
    catch (Exception e)
    {
        newException = handler(e);
    }
    throw newException;
}

// 普通版,无额外信息
JSONValue readConfig1(string s)
{
    // dfmt off
    return s
        .readText
        .parseJSON;
    // dfmt.on
}

// 用描述来包装
JSONValue readConfig2(string s)
{
    // dfmt off
    return s
        .readText
        .parseJSON
        .contextWithString("Cannot process config file %s".format(s));
    // dfmt on
}

// 去重复
JSONValue readConfig3(string s)
{
    // dfmt off
    auto t = s
        .readText;
    return t
        .parseJSON
        .contextWithString("Cannot process config file %s".format(s));
    // dfmt on
}

// 不同接口
JSONValue readConfig4(string s)
{
    // dfmt off
    auto t = s
        .readText;
    return t
        .parseJSON
        .contextWithException((Exception e) {
            return new Exception("Cannot process config file%s\n %s".format(s, e.msg));
        });
    // dfmt on
}

void main()
{
    foreach (file; [
        "normal.txt",
        "missing.txt",
        "broken_json.txt",
        "not_readable.txt",
        "invalid_utf8.txt",
    ])
    {

writeln("===============");
        size_t idx = 0;
        foreach (kv; [
            tuple("readConfig1", &readConfig1),
        tuple("readConfig2", &readConfig2),
        tuple("readConfig3", &readConfig3),
            tuple("readConfig4", &readConfig4),
        ])
        {
            auto f = kv[1];
            try
            {
                if (idx++ > 0) writeln("===");
                writeln("Working on ", file, " with ", kv[0]);
                f("testfiles/%s".format(file));
            }
            catch (Exception e)
            {
                writeln(e.msg);
            }
        }
    }
}
posted @   zjh6  阅读(10)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示