File size: 15,672 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Globalization;
using System.Management.Automation;
using System.Runtime.Serialization;

using Microsoft.Management.Infrastructure;

using Dbg = System.Management.Automation.Diagnostics;

namespace Microsoft.PowerShell.Cmdletization.Cim
{
    /// <summary>
    /// Represents an error during execution of a CIM job.
    /// </summary>
    public class CimJobException : SystemException, IContainsErrorRecord
    {
        #region Standard constructors and methods required for all exceptions

        /// <summary>
        /// Initializes a new instance of the <see cref="CimJobException"/> class.
        /// </summary>
        public CimJobException() : this(null, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CimJobException"/> class with a specified error message.
        /// </summary>
        /// <param name="message">The message that describes the error.</param>
        public CimJobException(string message) : this(message, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CimJobException"/> class with a specified error message.
        /// </summary>
        /// <param name="message">The message that describes the error.</param>
        /// <param name="inner">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
        public CimJobException(string message, Exception inner) : base(message, inner)
        {
            InitializeErrorRecord(null, "CimJob_ExternalError", ErrorCategory.NotSpecified);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CimJobException"/> class with serialized data.
        /// </summary>
        /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
        /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
        [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")]
        protected CimJobException(
            SerializationInfo info,
            StreamingContext context)
        {
            throw new NotSupportedException();
        }

        #endregion

        internal static CimJobException CreateFromCimException(
            string jobDescription,
            CimJobContext jobContext,
            CimException cimException)
        {
            Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null");
            Dbg.Assert(jobContext != null, "Caller should verify jobContext != null");
            Dbg.Assert(cimException != null, "Caller should verify cimException != null");

            string message = BuildErrorMessage(jobDescription, jobContext, cimException.Message);
            CimJobException cimJobException = new(message, cimException);
            cimJobException.InitializeErrorRecord(jobContext, cimException);
            return cimJobException;
        }

        internal static CimJobException CreateFromAnyException(
            string jobDescription,
            CimJobContext jobContext,
            Exception inner)
        {
            Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null");
            Dbg.Assert(jobContext != null, "Caller should verify jobContext != null");
            Dbg.Assert(inner != null, "Caller should verify inner != null");

            if (inner is CimException cimException)
            {
                return CreateFromCimException(jobDescription, jobContext, cimException);
            }

            string message = BuildErrorMessage(jobDescription, jobContext, inner.Message);
            CimJobException cimJobException = new(message, inner);
            if (inner is IContainsErrorRecord containsErrorRecord)
            {
                cimJobException.InitializeErrorRecord(
                    jobContext,
                    errorId: "CimJob_" + containsErrorRecord.ErrorRecord.FullyQualifiedErrorId,
                    errorCategory: containsErrorRecord.ErrorRecord.CategoryInfo.Category);
            }
            else
            {
                cimJobException.InitializeErrorRecord(
                    jobContext,
                    errorId: "CimJob_" + inner.GetType().Name,
                    errorCategory: ErrorCategory.NotSpecified);
            }

            return cimJobException;
        }

        internal static CimJobException CreateWithFullControl(
            CimJobContext jobContext,
            string message,
            string errorId,
            ErrorCategory errorCategory,
            Exception inner = null)
        {
            Dbg.Assert(jobContext != null, "Caller should verify jobContext != null");
            Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null");
            Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null");

            CimJobException cimJobException = new(jobContext.PrependComputerNameToMessage(message), inner);
            cimJobException.InitializeErrorRecord(jobContext, errorId, errorCategory);
            return cimJobException;
        }

        internal static CimJobException CreateWithoutJobContext(
            string message,
            string errorId,
            ErrorCategory errorCategory,
            Exception inner = null)
        {
            Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null");
            Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null");

            CimJobException cimJobException = new(message, inner);
            cimJobException.InitializeErrorRecord(null, errorId, errorCategory);
            return cimJobException;
        }

        internal static CimJobException CreateFromMethodErrorCode(string jobDescription, CimJobContext jobContext, string methodName, string errorCodeFromMethod)
        {
            string rawErrorMessage = string.Format(
                CultureInfo.InvariantCulture,
                CmdletizationResources.CimJob_ErrorCodeFromMethod,
                errorCodeFromMethod);

            string errorMessage = BuildErrorMessage(jobDescription, jobContext, rawErrorMessage);

            CimJobException cje = new(errorMessage);
            cje.InitializeErrorRecord(jobContext, "CimJob_" + methodName + "_" + errorCodeFromMethod, ErrorCategory.InvalidResult);

            return cje;
        }

        private static string BuildErrorMessage(string jobDescription, CimJobContext jobContext, string errorMessage)
        {
            Dbg.Assert(!string.IsNullOrEmpty(errorMessage), "Caller should verify !string.IsNullOrEmpty(errorMessage)");

            if (string.IsNullOrEmpty(jobDescription))
            {
                return jobContext.PrependComputerNameToMessage(errorMessage);
            }
            else
            {
                string errorMessageWithJobDescription = string.Format(
                    CultureInfo.InvariantCulture,
                    CmdletizationResources.CimJob_GenericCimFailure,
                    errorMessage,
                    jobDescription);
                return jobContext.PrependComputerNameToMessage(errorMessageWithJobDescription);
            }
        }

        private void InitializeErrorRecordCore(CimJobContext jobContext, Exception exception, string errorId, ErrorCategory errorCategory)
        {
            ErrorRecord coreErrorRecord = new(
                exception: exception,
                errorId: errorId,
                errorCategory: errorCategory,
                targetObject: jobContext?.TargetObject);

            if (jobContext != null)
            {
                System.Management.Automation.Remoting.OriginInfo originInfo = new(
                    jobContext.Session.ComputerName,
                    Guid.Empty);

                _errorRecord = new System.Management.Automation.Runspaces.RemotingErrorRecord(
                    coreErrorRecord,
                    originInfo);

                _errorRecord.SetInvocationInfo(jobContext.CmdletInvocationInfo);
                _errorRecord.PreserveInvocationInfoOnce = true;
            }
            else
            {
                _errorRecord = coreErrorRecord;
            }
        }

        private void InitializeErrorRecord(CimJobContext jobContext, string errorId, ErrorCategory errorCategory)
        {
            InitializeErrorRecordCore(
                jobContext: jobContext,
                exception: this,
                errorId: errorId,
                errorCategory: errorCategory);
        }

        private void InitializeErrorRecord(CimJobContext jobContext, CimException cimException)
        {
            InitializeErrorRecordCore(
                jobContext: jobContext,
                exception: cimException,
                errorId: cimException.MessageId ?? "MiClientApiError_" + cimException.NativeErrorCode,
                errorCategory: ConvertCimExceptionToErrorCategory(cimException));

            if (cimException.ErrorData != null)
            {
                _errorRecord.CategoryInfo.TargetName = cimException.ErrorSource;
                _errorRecord.CategoryInfo.TargetType = jobContext?.CmdletizationClassName;
            }
        }

        private static ErrorCategory ConvertCimExceptionToErrorCategory(CimException cimException)
        {
            ErrorCategory result = ErrorCategory.NotSpecified;

            if (cimException.ErrorData != null)
            {
                result = ConvertCimErrorToErrorCategory(cimException.ErrorData);
            }

            if (result == ErrorCategory.NotSpecified)
            {
                result = ConvertCimNativeErrorCodeToErrorCategory(cimException.NativeErrorCode);
            }

            return result;
        }

        private static ErrorCategory ConvertCimNativeErrorCodeToErrorCategory(NativeErrorCode nativeErrorCode)
        {
            switch (nativeErrorCode)
            {
                case NativeErrorCode.Ok:
                    return ErrorCategory.NotSpecified;
                case NativeErrorCode.Failed:
                    return ErrorCategory.NotSpecified;
                case NativeErrorCode.AccessDenied:
                    return ErrorCategory.PermissionDenied;
                case NativeErrorCode.InvalidNamespace:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.InvalidParameter:
                    return ErrorCategory.InvalidArgument;
                case NativeErrorCode.InvalidClass:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.NotFound:
                    return ErrorCategory.ObjectNotFound;
                case NativeErrorCode.NotSupported:
                    return ErrorCategory.NotImplemented;
                case NativeErrorCode.ClassHasChildren:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.ClassHasInstances:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.InvalidSuperClass:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.AlreadyExists:
                    return ErrorCategory.ResourceExists;
                case NativeErrorCode.NoSuchProperty:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.TypeMismatch:
                    return ErrorCategory.InvalidType;
                case NativeErrorCode.QueryLanguageNotSupported:
                    return ErrorCategory.NotImplemented;
                case NativeErrorCode.InvalidQuery:
                    return ErrorCategory.InvalidArgument;
                case NativeErrorCode.MethodNotAvailable:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.MethodNotFound:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.NamespaceNotEmpty:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.InvalidEnumerationContext:
                    return ErrorCategory.MetadataError;
                case NativeErrorCode.InvalidOperationTimeout:
                    return ErrorCategory.InvalidArgument;
                case NativeErrorCode.PullHasBeenAbandoned:
                    return ErrorCategory.OperationStopped;
                case NativeErrorCode.PullCannotBeAbandoned:
                    return ErrorCategory.CloseError;
                case NativeErrorCode.FilteredEnumerationNotSupported:
                    return ErrorCategory.NotImplemented;
                case NativeErrorCode.ContinuationOnErrorNotSupported:
                    return ErrorCategory.NotImplemented;
                case NativeErrorCode.ServerLimitsExceeded:
                    return ErrorCategory.ResourceBusy;
                case NativeErrorCode.ServerIsShuttingDown:
                    return ErrorCategory.ResourceUnavailable;
                default:
                    return ErrorCategory.NotSpecified;
            }
        }

        private static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimError)
        {
            if (cimError == null)
            {
                return ErrorCategory.NotSpecified;
            }

            CimProperty errorCategoryProperty = cimError.CimInstanceProperties["Error_Category"];
            if (errorCategoryProperty == null)
            {
                return ErrorCategory.NotSpecified;
            }

            ErrorCategory errorCategoryValue;
            if (!LanguagePrimitives.TryConvertTo<ErrorCategory>(errorCategoryProperty.Value, CultureInfo.InvariantCulture, out errorCategoryValue))
            {
                return ErrorCategory.NotSpecified;
            }

            return errorCategoryValue;
        }

        /// <summary>
        /// <see cref="ErrorRecord"/> which provides additional information about the error.
        /// </summary>
        public ErrorRecord ErrorRecord
        {
            get { return _errorRecord; }
        }

        private ErrorRecord _errorRecord;

        internal bool IsTerminatingError
        {
            get
            {
                if ((this.InnerException is not CimException cimException) || (cimException.ErrorData == null))
                {
                    return false;
                }

                CimProperty perceivedSeverityProperty = cimException.ErrorData.CimInstanceProperties["PerceivedSeverity"];
                if ((perceivedSeverityProperty == null) || (perceivedSeverityProperty.CimType != CimType.UInt16) || (perceivedSeverityProperty.Value == null))
                {
                    return false;
                }

                ushort perceivedSeverityValue = (ushort)perceivedSeverityProperty.Value;
                if (perceivedSeverityValue != 7)
                {
                    /* from CIM Schema: Interop\CIM_Error.mof:
                         "7 - Fatal/NonRecoverable should be used to indicate an "
                          "error occurred, but it\'s too late to take remedial "
                          "action. \n"
                     */
                    return false;
                }

                return true;
            }
        }
    }
}