-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathJsonExceptionHandler.cs
59 lines (48 loc) · 1.85 KB
/
JsonExceptionHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using Godot;
using System.IO;
using System.Text;
using System;
using System.Text.Json;
namespace RedotUtils;
public class JsonExceptionHandler
{
public static void Handle(JsonException ex, string jsonText, string path)
{
// Extract relevant information from the exception
long? lineNumber = ex.LineNumber;
if (lineNumber.HasValue)
{
// Split the JSON into lines
string[] lines = jsonText.Split('\n');
// Get the problematic line
string problematicLine = lines[lineNumber.Value - 1];
// Determine the range of lines to display
int startLine = Math.Max(0, (int)lineNumber.Value - 7);
int endLine = Math.Min(lines.Length, (int)lineNumber.Value + 7);
// Create the error message
StringBuilder errorMessage = new();
errorMessage.AppendLine($"ERROR: Failed to parse {Path.GetFileName(path)}");
errorMessage.AppendLine();
errorMessage.AppendLine($"{ex.Message}");
errorMessage.AppendLine();
// Add the lines before the problematic line
for (int i = startLine; i < lineNumber.Value - 1; i++)
{
errorMessage.AppendLine(lines[i]);
}
// Add the problematic line with the caret indicating the error position
errorMessage.AppendLine($"{problematicLine} <--- Syntax error could be on this line or the next line");
// Add the lines after the problematic line
for (int i = (int)lineNumber.Value; i < endLine; i++)
{
errorMessage.AppendLine(lines[i]);
}
GD.Print(errorMessage);
}
else
{
GD.Print($"ERROR: Failed to parse {Path.GetFileName(path)}");
GD.Print(ex.Message);
}
}
}