I made a class to conviniently serialize/deserialize data. Now I'm stuck with the following question. Should I handle exceptions (use try-catch) inside JsonStorage
or inside ConfigManager
and other classes that might use JsonStorage
in the future?
public class JsonStorage : IDataStorage
{
private readonly IFileSystem fileSystem;
private readonly ILogger logger;
public JsonStorage(IFileSystem fileSystem, ILogger logger)
{
this.fileSystem = fileSystem;
this.logger = logger;
}
public T RestoreObject<T>(string path)
{
T result = default;
try
{
if (!fileSystem.Path.IsPathFullyQualified(path))
throw new ArgumentException("Invalid path.", nameof(path));
string json = fileSystem.File.ReadAllText($"{path}.json");
result = JsonConvert.DeserializeObject<T>(json);
}
catch (Exception ex)
{
logger.Log($"Object can't be restored. {ex.Message}");
}
return result;
}
public void StoreObject(object obj, string path)
{
string file = $"{path}.json";
try
{
if (!fileSystem.Path.IsPathFullyQualified(path))
throw new ArgumentException("Invalid path.", nameof(path));
fileSystem.Directory.CreateDirectory(fileSystem.Path.GetDirectoryName(file));
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
fileSystem.File.WriteAllText(file, json);
}
catch (Exception ex)
{
logger.Log($"Object can't be stored. {ex.Message}");
}
}
}
public static class ConfigManager
{
private static readonly string configPath = @"SomePath\Config";
public static BotConfig LoadConfig()
{
return Unity.Resolve<IDataStorage>().RestoreObject<BotConfig>(configPath);
}
public static void SaveConfig(BotConfig config)
{
Unity.Resolve<IDataStorage>().StoreObject(config, configPath);
}
}
ConfigManager
- example class that holds a path to Config.json and loads/saves it (using JsonStorage
internaly).
For now I'm catching exceptions inside JsonStorage
and using a logger instance to print exception messages to the console.
I don't know if there's a downside to that. Should JsonStorage
have its own logger? Should it throw an exception (just like ReadAllText
/WriteAllText
) when something goes wrong with path/files?
Or maybe there is a good practice and some better ways to handle exceptions (in my particular case)?