原文
#!/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)
{
return s
.readText
.parseJSON;
}
JSONValue readConfig2(string s)
{
return s
.readText
.parseJSON
.contextWithString("Cannot process config file %s".format(s));
}
JSONValue readConfig3(string s)
{
auto t = s
.readText;
return t
.parseJSON
.contextWithString("Cannot process config file %s".format(s));
}
JSONValue readConfig4(string s)
{
auto t = s
.readText;
return t
.parseJSON
.contextWithException((Exception e) {
return new Exception("Cannot process config file%s\n %s".format(s, e.msg));
});
}
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);
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现