source

Catching FULL 예외 메시지

itover 2023. 4. 22. 09:21
반응형

Catching FULL 예외 메시지

고려사항:

Invoke-WebRequest $sumoApiURL -Headers @{"Content-Type"= "application/json"} -Credential $cred -WebSession $webRequestSession -Method post -Body $sumojson -ErrorAction Stop

이로 인해 다음 예외가 발생합니다.

여기에 이미지 설명을 입력하십시오.

어떻게 하면 완전히 잡을 수 있고 적어도 "같은 이름의 리소스가 이미 존재합니다"를 걸러낼 수 있을까요?

사용.$_.Exception.GetType().FullName수율

System.Net.Web Exception(웹 예외)

그리고.$_.Exception.Message주다

리모트 서버에서 (400) Bad Request 오류가 반환되었습니다.

PowerShell 오류 및 예외는 구조화된 개체입니다.콘솔에 표시되는 오류 메시지는 실제로는 오류/예외 개체의 여러 요소에서 가져온 정보를 포함하는 형식화된 메시지입니다.다음과 같이 직접 구성할 수 있습니다.

$formatstring = "{0} : {1}`n{2}`n" +
                "    + CategoryInfo          : {3}`n" +
                "    + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
          $_.ErrorDetails.Message,
          $_.InvocationInfo.PositionMessage,
          $_.CategoryInfo.ToString(),
          $_.FullyQualifiedErrorId

$formatstring -f $fields

에러 메시지를 표시하는 것만으로catchblock 현재 객체 변수(그 시점에서 오류가 유지됨)를 에코하기만 하면 됩니다.

try {
  ...
} catch {
  $_
}

컬러 출력이 필요한 경우Write-Host위에서 설명한 포맷된 문자열로 지정합니다.

try {
  ...
} catch {
  ...
  Write-Host -Foreground Red -Background Black ($formatstring -f $fields)
}

이와 같이, 통상, 예외 핸들러에 에러 메세지가 있는 그대로의 표시는 하고 싶지 않습니다(그렇지 않은 경우는,-ErrorAction Stop무의미할 것이다).구조화된 오류/예외 개체는 보다 나은 오류 제어에 사용할 수 있는 추가 정보를 제공합니다.예를 들면$_.Exception.HResult실제 에러 번호를 지정합니다. $_.ScriptStackTrace그리고.$_.Exception.StackTrace디버깅 시 스택트레이스를 표시할 수 있습니다. $_.Exception.InnerException에서는 오류에 대한 추가 정보가 포함된 중첩된 예외에 액세스할 수 있습니다(최상위 수준의 PowerShell 오류는 다소 일반적일 수 있음).다음과 같이 중첩된 예외를 풀 수 있습니다.

$e = $_.Exception
$msg = $e.Message
while ($e.InnerException) {
  $e = $e.InnerException
  $msg += "`n" + $e.Message
}
$msg

당신의 경우, 추출하고 싶은 정보가 있는 것 같습니다.$_.ErrorDetails.Message오브젝트나 JSON 문자열이 있는지는 확실하지 않지만 멤버의 유형과 값에 대한 정보를 얻을 수 있을 것입니다.$_.ErrorDetails달려서

$_.ErrorDetails | Get-Member
$_.ErrorDetails | Format-List *

한다면$_.ErrorDetails.Message는 다음과 같은 메시지스트링을 얻을 수 있는 오브젝트입니다.

$_.ErrorDetails.Message.message

그렇지 않으면 먼저 JSON 문자열을 개체로 변환해야 합니다.

$_.ErrorDetails.Message | ConvertFrom-Json | Select-Object -Expand message

처리 중인 오류 유형에 따라 특정 유형의 예외에 당면한 문제에 대한 보다 구체적인 정보가 포함될 수도 있습니다.예를 들어, 고객님의 경우WebException에러 메시지($_.Exception.Message) 에는, 서버로부터의 실제의 응답이 격납되어 있습니다.

PS C:\> $e.예외 | 멤버 가져오기
유형 이름:시스템.Net.WebException
멤버 이름유형 정의----             ---------- ----------Method Bool Equals(시스템)와 동일합니다.오브젝트 obj), bool_Exception.이...GetBaseException 메서드시스템예외 GetBase예외(), 시스템.엑셀...
GetHashCode 메서드 int GetHashCode() 및 int _Exception.Get Hash Code()GetObjectData 메서드 void GetObjectData(시스템).런타임시리얼화S...GetType 메서드유형 GetType()을 입력하고 _Exception을 입력합니다.GetType()ToString 메서드 문자열 ToString() 및 문자열 _Exception.ToString()데이터 속성 시스템.컬렉션IDIA 데이터 {get;}HelpLink 속성 문자열 HelpLink {get;set;}HResult 속성 int HResult {get;}InnerException 속성 시스템.예외 InnerException {get;}메시지 속성 문자열 메시지 {get;}응답 속성 시스템.Net.WebResponse 응답 {get;}소스 속성 문자열 소스 {get;set;}StackTrace 속성 문자열 StackTrace {get;}상태 속성 시스템.Net.WebExceptionStatus 상태 {get;}Target Site 속성 시스템.반사.MethodBase TargetSite {get;}

다음과 같은 정보를 제공합니다.

PS C:\> $e.예외입니다.응답
IsMutualally(상호)인증필 : False쿠키: {}헤더: {Keep-Alive, Connection, Content-Length, Content-T...}서포트머리글 : TrueContent Length : 198Content Encoding :Content Type : 텍스트 / 텍스트; charset=iso-8859-1문자 세트 : iso-8859-1서버: Apache/2.4.10최종변경일 : 2017.07.2016 14:39:29상태 코드: 찾을 수 없음상태 설명: 찾을 수 없습니다.Protocol Version : 1.1Response Uri : http://www.example.com/방법 : POSTIsFromCache : False

모든 예외에 동일한 속성 세트가 있는 것은 아니기 때문에 특정 예외에 대해 특정 핸들러를 사용할 수 있습니다.

try {
  ...
} catch [System.ArgumentException] {
  # handle argument exceptions
} catch [System.Net.WebException] {
  # handle web exceptions
} catch {
  # handle all other exceptions
}

조작(을 닫는 이 있는 경우는, 에 넣을 수.finally'이것'은 다음과 같습니다.

try {
  ...
} catch {
  ...
} finally {
  # cleanup operations go here
}

찾았다!

됩니다.$Error[0]에러 메세지가 표시됩니다.

옵션 1: 심플하지만 효과적이며 대부분의 용도에 적합

try {1/0} catch { $_ | Format-List * -Force | Out-String }

결과:

PSMessageDetails      :
Exception             : System.Management.Automation.RuntimeException: Attempted to divide by zero. ---> System.DivideByZeroException: Attempted to divide by zero.
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
                           at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          :
CategoryInfo          : NotSpecified: (:) [], RuntimeException
FullyQualifiedErrorId : RuntimeException
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}

옵션 2: 호출 정보도 인쇄합니다.

try {1/0} catch { $_ | Format-List * -Force | Out-String ; $_.InvocationInfo | Format-List * -Force | Out-String }

결과:

PSMessageDetails      :
Exception             : System.Management.Automation.RuntimeException: Attempted to divide by zero. ---> System.DivideByZeroException: Attempted to divide by zero.
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
                           at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          :
CategoryInfo          : NotSpecified: (:) [], RuntimeException
FullyQualifiedErrorId : RuntimeException
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}





MyCommand             :
BoundParameters       : {}
UnboundArguments      : {}
ScriptLineNumber      : 1
OffsetInLine          : 6
HistoryId             : -1
ScriptName            :
Line                  : try {1/0} catch { $_ | Format-List * -Force | Out-String ; $_.InvocationInfo | Format-List * -Force | Out-String }
PositionMessage       : At line:1 char:6
                        + try {1/0} catch { $_ | Format-List * -Force | Out-String ; $_.Invocat ...
                        +      ~~~
PSScriptRoot          :
PSCommandPath         :
InvocationName        :
PipelineLength        : 0
PipelinePosition      : 0
ExpectingInput        : False
CommandOrigin         : Internal
DisplayScriptPosition :

옵션 3: 위의 양쪽과 모든 내부 예외

try {1/0} catch { $Exception = $_; $Exception | Format-List * -Force | Out-String ; $Exception.InvocationInfo | Format-List * -Force | Out-String ; for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException)) { Write-Host ("$i" * 80) ; $Exception | Format-List * -Force | Out-String } }

PSMessageDetails      :
Exception             : System.Management.Automation.RuntimeException: Attempted to divide by zero. ---> System.DivideByZeroException: Attempted to divide by zero.
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
                           at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          :
CategoryInfo          : NotSpecified: (:) [], RuntimeException
FullyQualifiedErrorId : RuntimeException
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}





MyCommand             :
BoundParameters       : {}
UnboundArguments      : {}
ScriptLineNumber      : 1
OffsetInLine          : 6
HistoryId             : -1
ScriptName            :
Line                  : try {1/0} catch { $Exception = $_; $Exception | Format-List * -Force | Out-String ; $Exception.InvocationInfo | Format-List * -Force | Out-String ; for ($i = 0; $Exception;
                        $i++, ($Exception = $Exception.InnerException)) { Write-Host ("$i" * 80) ; $Exception | Format-List * -Force | Out-String  }  }
PositionMessage       : At line:1 char:6
                        + try {1/0} catch { $Exception = $_; $Exception | Format-List * -Force  ...
                        +      ~~~
PSScriptRoot          :
PSCommandPath         :
InvocationName        :
PipelineLength        : 0
PipelinePosition      : 0
ExpectingInput        : False
CommandOrigin         : Internal
DisplayScriptPosition :




00000000000000000000000000000000000000000000000000000000000000000000000000000000


PSMessageDetails      :
Exception             : System.Management.Automation.RuntimeException: Attempted to divide by zero. ---> System.DivideByZeroException: Attempted to divide by zero.
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
                           at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject          :
CategoryInfo          : NotSpecified: (:) [], RuntimeException
FullyQualifiedErrorId : RuntimeException
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}

다음과 같은 것이 나에게 잘 통했다.

try {
    asdf
} catch {
    $string_err = $_ | Out-String
}

write-host $string_err

그 결과 Error Record 객체가 아닌 문자열로서 다음과 같이 됩니다.

asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+     asdf
+     ~~~~
    + CategoryInfo          : ObjectNotFound: (asdf:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

저는 계속해서 이러한 질문으로 돌아가 제가 관심 있는 데이터가 정말로 획일적인 Error Record 구조 중 어디에 숨겨져 있는지 알아내려고 합니다.거의 모든 답변이 특정 데이터 비트를 추출하는 방법에 대한 단편적인 지침을 제공합니다.

하지만 이 물건 전체를 버리면 큰 도움이 된다는 걸 깨달았어요ConvertTo-Json말 그대로 모든 것을 이해할 수 있는 레이아웃으로 시각적으로 볼 수 있습니다.

    try {
        Invoke-WebRequest...
    }
    catch {
        Write-Host ($_ | ConvertTo-Json)
    }

ConvertTo-Json의 »-Depth는 더 값을 인 "Default Depth" ("Default Depth")를 초과하여 해 주십시오.2:P

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json

다음 항목을 추가할 수 있습니다.

-ErrorVariable errvar

그리고 안을 들여다봐$errvar.

언급URL : https://stackoverflow.com/questions/38419325/catching-full-exception-message

반응형