我需要实现某种解决方案,以便在满足某些条件时在我们的业务逻辑层中返回一条错误消息。
该错误消息应该可以在文件或表格中配置,如果需要可以在运行时编辑。
我以前见过它以几种方式完成,它总是以“此错误消息是 {0}”之类的结尾,然后当开发人员使用消息时,他们不一定知道有多少(如果有)参数消息需要。
只是希望利用可能已经完成的事情,我不认为 .net 框架中已经有提供者或任何东西。
最佳答案
一个解决方案;
使用这样的命名占位符存储您的错误消息;
- “这是一个错误 {name1}。Andkg kfkjgkf {name2}”
- “这是一些 {size} 的问题”
然后您需要一个在其构造函数中接受原始错误消息的类,例如“这是一些 {size} 问题”。
然后该类将允许开发人员为每个占位符指定值。
最后,开发人员将调用一个方法,用指定的值替换占位符并返回结果。
即
var rawMessage = "this is some {size} problem"; // fetch this from a file, db, or build runtime
var errorMessage = new ErrorMessage(rawMessage); // finds all the placeholders, stores them in a Dictionary<string, string>
errorMessage.SetPlaceholderValue("size", "big"); // sets the {size} placeholder value
var message = errorMessage.BuildErrorMessage(); // replaces placeholders with values and checks no values are missing
// message should look like "this is some big problem";
// this will handle any number of placeholders
关于.net 可配置业务错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3020186/