|
1 | 1 | // Licensed to the .NET Foundation under one or more agreements. |
2 | 2 | // The .NET Foundation licenses this file to you under the MIT license. |
3 | 3 |
|
| 4 | +using Docfx.Common; |
4 | 5 | using Spectre.Console; |
5 | 6 | using Spectre.Console.Cli; |
6 | 7 |
|
@@ -39,26 +40,34 @@ internal static int Main(string[] args) |
39 | 40 |
|
40 | 41 | static void OnException(Exception e, ITypeResolver? resolver) |
41 | 42 | { |
42 | | - if (e is CommandAppException cae) |
| 43 | + // Try to unwrap AggregateException. |
| 44 | + if (e is AggregateException ae && ae.InnerExceptions.Count == 1) |
| 45 | + e = ae.InnerExceptions[0]; |
| 46 | + |
| 47 | + if (!Console.IsOutputRedirected) |
43 | 48 | { |
44 | | - if (cae.Pretty is { } pretty) |
45 | | - AnsiConsole.Write(pretty); |
46 | | - else |
47 | | - AnsiConsole.MarkupInterpolated($"[red]Error:[/] {e.Message}"); |
| 49 | + // Write exception to console. |
| 50 | + AnsiConsole.Console.WriteException(e); |
| 51 | + |
| 52 | + // Write exception to ReportLogListener if exists. |
| 53 | + var reportLogListener = Logger.FindListener(x => x is ReportLogListener); |
| 54 | + reportLogListener?.WriteLine(Logger.GetLogItem(LogLevel.Error, e.ToString(), code: ErrorCodes.Build.FatalError)); |
48 | 55 | } |
49 | 56 | else |
50 | 57 | { |
51 | | - AnsiConsole.WriteException(e, new ExceptionSettings() |
52 | | - { |
53 | | - Format = ExceptionFormats.ShortenEverything, |
54 | | - Style = new() |
55 | | - { |
56 | | - ParameterName = Color.Grey, |
57 | | - ParameterType = Color.Grey78, |
58 | | - LineNumber = Color.Grey78, |
59 | | - }, |
60 | | - }); |
| 58 | + // Write exception with Logger API if stdout is redirected. |
| 59 | + // To avoid line wrap issue https://github.com/spectreconsole/spectre.console/issues/1782 |
| 60 | + var exceptions = e is AggregateException ae2 |
| 61 | + ? ae2.Flatten().InnerExceptions.ToArray() |
| 62 | + : [e]; |
| 63 | + |
| 64 | + foreach (var ex in exceptions) |
| 65 | + Logger.LogError(e.ToString(), code: ErrorCodes.Build.FatalError); |
61 | 66 | } |
| 67 | + |
| 68 | + // Cleanup logger. |
| 69 | + Logger.Flush(); |
| 70 | + Logger.UnregisterAllListeners(); |
62 | 71 | } |
63 | 72 | } |
64 | 73 | } |
0 commit comments