Skip to content

Commit

Permalink
Improved exception handling (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
dimonovdd authored Oct 21, 2021
1 parent 89fdf00 commit a303c83
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 14 deletions.
17 changes: 17 additions & 0 deletions src/CompactJson/CompactJsonException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;

namespace MSBuild.CompactJsonResources
{
public class CompactJsonException : Exception
{
public CompactJsonException(string filePath, Exception inner)
:base(CreateMess(filePath, inner), inner)
{
}

static string CreateMess(string filePath, Exception inner) =>
$"Failed to process {filePath} See Build Output. {Environment.NewLine}" +
$"{inner.GetType()}: {inner.Message}";
}
}

35 changes: 21 additions & 14 deletions src/CompactJson/JsonFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,24 +54,31 @@ public JsonFile(string link, string filename, string extension, string fullPath,

public TaskItem WriteCompactTempFile()
{
using var frs = File.OpenRead(FullPath);
using var jDoc = JsonDocument.Parse(frs,
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });

var directory = Path.GetDirectoryName(TempFullPath);
try
{
using var frs = File.OpenRead(FullPath);
using var jDoc = JsonDocument.Parse(frs,
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });

if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
var directory = Path.GetDirectoryName(TempFullPath);

if (File.Exists(TempFullPath))
File.Delete(TempFullPath);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);

using var fws = File.OpenWrite(TempFullPath);
using var writer = new Utf8JsonWriter(fws);
jDoc.WriteTo(writer);
writer.Flush();
fws.Flush();
if (File.Exists(TempFullPath))
File.Delete(TempFullPath);

using var fws = File.OpenWrite(TempFullPath);
using var writer = new Utf8JsonWriter(fws);
jDoc.WriteTo(writer);
writer.Flush();
fws.Flush();
}
catch(Exception ex)
{
throw new CompactJsonException(FullPath, ex);
}

return GetTaskItem();
}

Expand Down

0 comments on commit a303c83

Please sign in to comment.