Skip to content

Commit abd6f50

Browse files
committed
Clean up code to bubble up exceptions to the global catch block
1 parent f683b72 commit abd6f50

File tree

1 file changed

+103
-113
lines changed

1 file changed

+103
-113
lines changed

src/Microsoft.OpenApi.Hidi/OpenApiService.cs

Lines changed: 103 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -59,131 +59,131 @@ CancellationToken cancellationToken
5959
{
6060
throw new IOException($"The file {output} already exists. Please input a new file path.");
6161
}
62-
}
63-
catch (Exception ex)
64-
{
65-
#if DEBUG
66-
logger.LogCritical(ex, ex.Message);
67-
#else
68-
logger.LogCritical(ex.Message);
69-
#endif
70-
return;
71-
}
7262

73-
Stream stream;
74-
OpenApiDocument document;
75-
OpenApiFormat openApiFormat;
76-
var stopwatch = new Stopwatch();
77-
78-
if (!string.IsNullOrEmpty(csdl))
79-
{
80-
// Default to yaml and OpenApiVersion 3 during csdl to OpenApi conversion
81-
openApiFormat = format ?? GetOpenApiFormat(csdl, logger);
82-
version ??= OpenApiSpecVersion.OpenApi3_0;
83-
84-
stream = await GetStream(csdl, logger, cancellationToken);
85-
document = await ConvertCsdlToOpenApi(stream);
86-
}
87-
else
88-
{
89-
stream = await GetStream(openapi, logger, cancellationToken);
63+
Stream stream;
64+
OpenApiDocument document;
65+
OpenApiFormat openApiFormat;
66+
var stopwatch = new Stopwatch();
9067

91-
// Parsing OpenAPI file
92-
stopwatch.Start();
93-
logger.LogTrace("Parsing OpenApi file");
94-
var result = new OpenApiStreamReader(new OpenApiReaderSettings
68+
if (!string.IsNullOrEmpty(csdl))
9569
{
96-
ReferenceResolution = resolveexternal ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences,
97-
RuleSet = ValidationRuleSet.GetDefaultRuleSet()
70+
// Default to yaml and OpenApiVersion 3 during csdl to OpenApi conversion
71+
openApiFormat = format ?? GetOpenApiFormat(csdl, logger);
72+
version ??= OpenApiSpecVersion.OpenApi3_0;
73+
74+
stream = await GetStream(csdl, logger, cancellationToken);
75+
document = await ConvertCsdlToOpenApi(stream);
9876
}
99-
).ReadAsync(stream).GetAwaiter().GetResult();
77+
else
78+
{
79+
stream = await GetStream(openapi, logger, cancellationToken);
10080

101-
document = result.OpenApiDocument;
102-
stopwatch.Stop();
81+
// Parsing OpenAPI file
82+
stopwatch.Start();
83+
logger.LogTrace("Parsing OpenApi file");
84+
var result = new OpenApiStreamReader(new OpenApiReaderSettings
85+
{
86+
ReferenceResolution = resolveexternal ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences,
87+
RuleSet = ValidationRuleSet.GetDefaultRuleSet()
88+
}
89+
).ReadAsync(stream).GetAwaiter().GetResult();
10390

104-
var context = result.OpenApiDiagnostic;
105-
if (context.Errors.Count > 0)
106-
{
107-
logger.LogTrace("{timestamp}ms: Parsed OpenAPI with errors. {count} paths found.", stopwatch.ElapsedMilliseconds, document.Paths.Count);
91+
document = result.OpenApiDocument;
92+
stopwatch.Stop();
10893

109-
var errorReport = new StringBuilder();
94+
var context = result.OpenApiDiagnostic;
95+
if (context.Errors.Count > 0)
96+
{
97+
logger.LogTrace("{timestamp}ms: Parsed OpenAPI with errors. {count} paths found.", stopwatch.ElapsedMilliseconds, document.Paths.Count);
11098

111-
foreach (var error in context.Errors)
99+
var errorReport = new StringBuilder();
100+
101+
foreach (var error in context.Errors)
102+
{
103+
logger.LogError("OpenApi Parsing error: {message}", error.ToString());
104+
errorReport.AppendLine(error.ToString());
105+
}
106+
logger.LogError($"{stopwatch.ElapsedMilliseconds}ms: OpenApi Parsing errors {string.Join(Environment.NewLine, context.Errors.Select(e => e.Message).ToArray())}");
107+
}
108+
else
112109
{
113-
logger.LogError("OpenApi Parsing error: {message}", error.ToString());
114-
errorReport.AppendLine(error.ToString());
110+
logger.LogTrace("{timestamp}ms: Parsed OpenApi successfully. {count} paths found.", stopwatch.ElapsedMilliseconds, document.Paths.Count);
115111
}
116-
logger.LogError($"{stopwatch.ElapsedMilliseconds}ms: OpenApi Parsing errors {string.Join(Environment.NewLine, context.Errors.Select(e => e.Message).ToArray())}");
112+
113+
openApiFormat = format ?? GetOpenApiFormat(openapi, logger);
114+
version ??= result.OpenApiDiagnostic.SpecificationVersion;
117115
}
118-
else
116+
117+
Func<string, OperationType?, OpenApiOperation, bool> predicate;
118+
119+
// Check if filter options are provided, then slice the OpenAPI document
120+
if (!string.IsNullOrEmpty(filterbyoperationids) && !string.IsNullOrEmpty(filterbytags))
119121
{
120-
logger.LogTrace("{timestamp}ms: Parsed OpenApi successfully. {count} paths found.", stopwatch.ElapsedMilliseconds, document.Paths.Count);
122+
throw new InvalidOperationException("Cannot filter by operationIds and tags at the same time.");
121123
}
124+
if (!string.IsNullOrEmpty(filterbyoperationids))
125+
{
126+
logger.LogTrace("Creating predicate based on the operationIds supplied.");
127+
predicate = OpenApiFilterService.CreatePredicate(operationIds: filterbyoperationids);
122128

123-
openApiFormat = format ?? GetOpenApiFormat(openapi, logger);
124-
version ??= result.OpenApiDiagnostic.SpecificationVersion;
125-
}
126-
127-
Func<string, OperationType?, OpenApiOperation, bool> predicate;
129+
logger.LogTrace("Creating subset OpenApi document.");
130+
document = OpenApiFilterService.CreateFilteredDocument(document, predicate);
131+
}
132+
if (!string.IsNullOrEmpty(filterbytags))
133+
{
134+
logger.LogTrace("Creating predicate based on the tags supplied.");
135+
predicate = OpenApiFilterService.CreatePredicate(tags: filterbytags);
128136

129-
// Check if filter options are provided, then slice the OpenAPI document
130-
if (!string.IsNullOrEmpty(filterbyoperationids) && !string.IsNullOrEmpty(filterbytags))
131-
{
132-
throw new InvalidOperationException("Cannot filter by operationIds and tags at the same time.");
133-
}
134-
if (!string.IsNullOrEmpty(filterbyoperationids))
135-
{
136-
logger.LogTrace("Creating predicate based on the operationIds supplied.");
137-
predicate = OpenApiFilterService.CreatePredicate(operationIds: filterbyoperationids);
137+
logger.LogTrace("Creating subset OpenApi document.");
138+
document = OpenApiFilterService.CreateFilteredDocument(document, predicate);
139+
}
140+
if (!string.IsNullOrEmpty(filterbycollection))
141+
{
142+
var fileStream = await GetStream(filterbycollection, logger, cancellationToken);
143+
var requestUrls = ParseJsonCollectionFile(fileStream, logger);
138144

139-
logger.LogTrace("Creating subset OpenApi document.");
140-
document = OpenApiFilterService.CreateFilteredDocument(document, predicate);
141-
}
142-
if (!string.IsNullOrEmpty(filterbytags))
143-
{
144-
logger.LogTrace("Creating predicate based on the tags supplied.");
145-
predicate = OpenApiFilterService.CreatePredicate(tags: filterbytags);
145+
logger.LogTrace("Creating predicate based on the paths and Http methods defined in the Postman collection.");
146+
predicate = OpenApiFilterService.CreatePredicate(requestUrls: requestUrls, source: document);
146147

147-
logger.LogTrace("Creating subset OpenApi document.");
148-
document = OpenApiFilterService.CreateFilteredDocument(document, predicate);
149-
}
150-
if (!string.IsNullOrEmpty(filterbycollection))
151-
{
152-
var fileStream = await GetStream(filterbycollection, logger, cancellationToken);
153-
var requestUrls = ParseJsonCollectionFile(fileStream, logger);
148+
logger.LogTrace("Creating subset OpenApi document.");
149+
document = OpenApiFilterService.CreateFilteredDocument(document, predicate);
150+
}
154151

155-
logger.LogTrace("Creating predicate based on the paths and Http methods defined in the Postman collection.");
156-
predicate = OpenApiFilterService.CreatePredicate(requestUrls: requestUrls, source:document);
152+
logger.LogTrace("Creating a new file");
153+
using var outputStream = output?.Create();
154+
var textWriter = outputStream != null ? new StreamWriter(outputStream) : Console.Out;
157155

158-
logger.LogTrace("Creating subset OpenApi document.");
159-
document = OpenApiFilterService.CreateFilteredDocument(document, predicate);
160-
}
161-
162-
logger.LogTrace("Creating a new file");
163-
using var outputStream = output?.Create();
164-
var textWriter = outputStream != null ? new StreamWriter(outputStream) : Console.Out;
156+
var settings = new OpenApiWriterSettings()
157+
{
158+
ReferenceInline = inline ? ReferenceInlineSetting.InlineLocalReferences : ReferenceInlineSetting.DoNotInlineReferences
159+
};
165160

166-
var settings = new OpenApiWriterSettings()
167-
{
168-
ReferenceInline = inline ? ReferenceInlineSetting.InlineLocalReferences : ReferenceInlineSetting.DoNotInlineReferences
169-
};
161+
IOpenApiWriter writer = openApiFormat switch
162+
{
163+
OpenApiFormat.Json => new OpenApiJsonWriter(textWriter, settings),
164+
OpenApiFormat.Yaml => new OpenApiYamlWriter(textWriter, settings),
165+
_ => throw new ArgumentException("Unknown format"),
166+
};
170167

171-
IOpenApiWriter writer = openApiFormat switch
172-
{
173-
OpenApiFormat.Json => new OpenApiJsonWriter(textWriter, settings),
174-
OpenApiFormat.Yaml => new OpenApiYamlWriter(textWriter, settings),
175-
_ => throw new ArgumentException("Unknown format"),
176-
};
168+
logger.LogTrace("Serializing to OpenApi document using the provided spec version and writer");
177169

178-
logger.LogTrace("Serializing to OpenApi document using the provided spec version and writer");
179-
180-
stopwatch.Start();
181-
document.Serialize(writer, (OpenApiSpecVersion)version);
182-
stopwatch.Stop();
170+
stopwatch.Start();
171+
document.Serialize(writer, (OpenApiSpecVersion)version);
172+
stopwatch.Stop();
183173

184-
logger.LogTrace($"Finished serializing in {stopwatch.ElapsedMilliseconds}ms");
174+
logger.LogTrace($"Finished serializing in {stopwatch.ElapsedMilliseconds}ms");
185175

186-
textWriter.Flush();
176+
textWriter.Flush();
177+
}
178+
catch (Exception ex)
179+
{
180+
#if DEBUG
181+
logger.LogCritical(ex, ex.Message);
182+
#else
183+
logger.LogCritical(ex.Message);
184+
#endif
185+
return;
186+
}
187187
}
188188

189189
/// <summary>
@@ -260,12 +260,7 @@ private static async Task<Stream> GetStream(string input, ILogger logger, Cancel
260260
}
261261
catch (HttpRequestException ex)
262262
{
263-
#if DEBUG
264-
logger.LogCritical(ex, "Could not download the file at {inputPath}, reason: {exMessage}", input, ex.Message);
265-
#else
266-
logger.LogCritical( "Could not download the file at {inputPath}, reason: {exMessage}", input, ex.Message);
267-
#endif
268-
return null;
263+
throw new InvalidOperationException($"Could not download the file at {input}", ex);
269264
}
270265
}
271266
else
@@ -283,12 +278,7 @@ ex is UnauthorizedAccessException ||
283278
ex is SecurityException ||
284279
ex is NotSupportedException)
285280
{
286-
#if DEBUG
287-
logger.LogCritical(ex, "Could not open the file at {inputPath}, reason: {exMessage}", input, ex.Message);
288-
#else
289-
logger.LogCritical("Could not open the file at {inputPath}, reason: {exMessage}", input, ex.Message);
290-
#endif
291-
return null;
281+
throw new InvalidOperationException($"Could not open the file at {input}", ex);
292282
}
293283
}
294284
stopwatch.Stop();

0 commit comments

Comments
 (0)