AppleScript NSError

[oc]エラーメッセージをダイアログに表示 エラー処理


【スクリプトエディタで開く】|

use AppleScript version "2.8"
use framework "Foundation"
use scripting additions
property refMe : a reference to current application


###エラーになるパス
set strFilePath to "~/Desktop/AAAA.text" as text
set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)

try
  
  set listDone to refMe's NSData's dataWithContentsOfURL:(ocidFilePathURL) options:0 |error|:(reference)
  
  
  set ocidNSErrorData to (item 2 of listDone)
  ##構文によっては item 3がエラー内容になる場合もある
  ## set ocidNSErrorData to (item 3 of listDone)
  if ocidNSErrorData is not (missing value) then
    set strResponse to ("") as text
    set strResponse to (("エラーコード:" & ocidNSErrorData's code())) as text
    set strResponse to (strResponse & "\r" & ("エラードメイン:" & ocidNSErrorData's domain())) as text
    set strResponse to (strResponse & "\r" & ("Description:" & ocidNSErrorData's localizedDescription())) as text
    set strResponse to (strResponse & "\r" & ("FailureReason:" & ocidNSErrorData's localizedFailureReason())) as text
    error strResponse
  end if
  ###エラーが発生したらダイアログにエラーメッセージを渡す
on error strResponse
  set aliasPathToMe to path to me as alias
  set strPathToMe to (POSIX path of aliasPathToMe) as text
  set strResponse to (strPathToMe & "\r" & strResponse) as text
  
  #####ダイアログを前面に
  set strAppName to (name of current application) as text
  ####スクリプトメニューから実行したら
  if strAppName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  set aliasIconPath to POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns" as alias
  display dialog "一部エラーが発生しました\r確認してください" with title "エラーメッセージ" default answer strResponse buttons {"OK", "キャンセル", "担当者にメールで送信"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 20 without hidden answer
  set strURL to ("mailto:?Body=" & strResponse & "&subject=【エラー報告】エラーが発生しました")
  tell application "Finder"
    open location strURL
  end tell
  
end try

|

[エラー対応]エラーデータ分解

set listDownLoadData to refNSData's dataWithContentsOfURL:ocidJsonURL options:0 |error|:(reference)

set ocidJsonData to (item 1 of listDownLoadData)


set ocidNSErrorData to item 2 of listDownLoadData
if ocidNSErrorData is not (missing value) then
doGetErrorData(ocidNSErrorData)
end if






to doGetErrorData(ocidNSErrorData)
#####個別のエラー情報
log "エラーコード:" & ocidNSErrorData's code() as text
log "エラードメイン:" & ocidNSErrorData's domain() as text
log "Description:" & ocidNSErrorData's localizedDescription() as text
log "FailureReason:" & ocidNSErrorData's localizedFailureReason() as text
log ocidNSErrorData's localizedRecoverySuggestion() as text
log ocidNSErrorData's localizedRecoveryOptions() as text
log ocidNSErrorData's recoveryAttempter() as text
log ocidNSErrorData's helpAnchor() as text
set ocidNSErrorUserInfo to ocidNSErrorData's userInfo()
set ocidAllValues to ocidNSErrorUserInfo's allValues() as list
set ocidAllKeys to ocidNSErrorUserInfo's allKeys() as list
repeat with ocidKeys in ocidAllKeys
if (ocidKeys as text) is "NSUnderlyingError" then
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedDescription() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedFailureReason() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoverySuggestion() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoveryOptions() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s recoveryAttempter() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s helpAnchor() as text
else
####それ以外の値はそのままテキストで読める
log (ocidKeys as text) & ": " & (ocidNSErrorUserInfo's valueForKey:ocidKeys) as text
end if
end repeat

end doGetErrorData

|

[Error]エラー番号

エラー番号の一覧はこちら
https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_error_codes.html


#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions






###キャンセルさせる
try

on error
error number -128
end try
####好きなメッセージでエラーさせる
try
log "エラーnumber200番台に空きがります"
on error
error "好きなメッセージでエラーさせる" number -200
end try

###returnで戻し
try

on error
return "好きなメッセージで処理終了"
end try

|

[NSError]エラーの情報を取得する

###戻り値にNSErrorが入る
|error|:(reference)
####エラーしても戻り値無し
|error|:(missing value)
想定できる箇所はmissing value 不安な箇所はreferenceとして使い分けが吉か?
#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions


property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSError : a reference to refMe's NSError
set objFileManager to refMe's NSFileManager's defaultManager()

set strDirPathA to do shell script "echo $HOME/Desktop/AAAAAAAAAAAAAA"
set strDirPathB to do shell script "echo $HOME/Desktop/BBBBBBBBBBBBBB"

do shell script "mkdir -pm 777 $HOME/Desktop/AAAAAAAAAAAAAA"
do shell script "mkdir -pm 777 $HOME/Desktop/BBBBBBBBBBBBBB"


###フォルダを定義
set ocidDirPathA to refNSString's stringWithString:strDirPathA
set ocidDirPathB to refNSString's stringWithString:strDirPathB
#####パス化する
set ocidPOSIXpathA to ocidDirPathA's stringByStandardizingPath
set ocidPOSIXpathB to ocidDirPathB's stringByStandardizingPath
####フォルダを作成
set listResult to (objFileManager's createDirectoryAtPath:ocidPOSIXpathA withIntermediateDirectories:true attributes:(missing value) |error|:(reference))
set listResult to (objFileManager's createDirectoryAtPath:ocidPOSIXpathB withIntermediateDirectories:true attributes:(missing value) |error|:(reference))
#####AAAAAAAAAAAAAA BBBBBBBBBBBBBBとしてリネーム(移動)しようとする-->エラー
set listResult to (objFileManager's moveItemAtPath:ocidPOSIXpathA toPath:ocidPOSIXpathB |error|:(reference))
####戻り値はリストで
##1つめがboolで失敗はfalse 成功はtrue
set listResult1 to item 1 of listResult
log listResult1
log class of listResult1
###2つ目にNSErrorの値が入る
set listResult2 to item 2 of listResult
log listResult2
log className() of listResult2 as text

if listResult1 is false then
#### item 1 of listResult falseなら移動が失敗のエラー
log listResult2's code() as text
log listResult2's domain() as text

set ocidUserInfo to listResult2's userInfo()
log ocidUserInfo as record
log className() of ocidUserInfo as text

set ocidAllValues to ocidUserInfo's allValues() as list
set ocidAllKeys to ocidUserInfo's allKeys() as list
###KEY"NSUnderlyingError"Valueの値がNSERRORなので個別に対応
repeat with ocidKeys in ocidAllKeys
if (ocidKeys as text) is "NSUnderlyingError" then
log (ocidUserInfo's valueForKey:ocidKeys)'s localizedDescription() as text
log (ocidUserInfo's valueForKey:ocidKeys)'s localizedFailureReason() as text
log (ocidUserInfo's valueForKey:ocidKeys)'s localizedRecoverySuggestion() as text
log (ocidUserInfo's valueForKey:ocidKeys)'s localizedRecoveryOptions() as text
log (ocidUserInfo's valueForKey:ocidKeys)'s recoveryAttempter() as text
log (ocidUserInfo's valueForKey:ocidKeys)'s helpAnchor() as text
else
####それ以外の値はそのままテキストで読める
log (ocidKeys as text) & ": " & (ocidUserInfo's valueForKey:ocidKeys) as text
end if
end repeat
#####その他個別の情報
log listResult2's localizedDescription() as text
log listResult2's localizedFailureReason() as text
log listResult2's localizedRecoverySuggestion() as text
log listResult2's localizedRecoveryOptions() as text
log listResult2's recoveryAttempter() as text
log listResult2's helpAnchor() as text

end if

|

その他のカテゴリー

Acrobat Acrobat Annotation Acrobat Dialog Acrobat Form Acrobat JS Acrobat Open Acrobat Plugin Acrobat python Acrobat Reader Acrobat Sequ Acrobat Stamps Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin System Information Admin Tools Admin Users Admin Volumes Adobe Apple AppleScript AppleScript Guide AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes AppleScript Automator AppleScript AVAsset AppleScript AVconvert AppleScript AVFoundation AppleScript AVURLAsset AppleScript BackUp AppleScript Barcode AppleScript Bash AppleScript Basic AppleScript Basic Path AppleScript Bluetooth AppleScript BOX AppleScript Browser AppleScript Calendar AppleScript CD/DVD AppleScript Choose AppleScript Chrome AppleScript CIImage AppleScript CloudStorage AppleScript Color AppleScript com.apple.LaunchServices.OpenWith AppleScript Console AppleScript Contacts AppleScript CotEditor AppleScript CURL AppleScript current application AppleScript Date&Time AppleScript delimiters AppleScript Desktop AppleScript Device AppleScript Disk AppleScript do shell script AppleScript Dock AppleScript DropBox AppleScript eMail AppleScript Encode Decode AppleScript Error AppleScript EXIFData AppleScript ffmpeg AppleScript File AppleScript Finder AppleScript Firefox AppleScript Folder AppleScript Fonts AppleScript GIF AppleScript HTML AppleScript Icon AppleScript Illustrator AppleScript Image Events AppleScript Image2PDF AppleScript ImageOptim Applescript iWork AppleScript Javascript AppleScript Jedit AppleScript Json AppleScript Label AppleScript List AppleScript locationd AppleScript LRC AppleScript LSSharedFileList AppleScript m3u8 AppleScript MakePDF AppleScript Map AppleScript Math AppleScript Microsoft AppleScript Microsoft Edge AppleScript Microsoft Excel AppleScript Mobileconfig AppleScript Mouse AppleScript Movie AppleScript Music AppleScript NetWork AppleScript Notes AppleScript NSArray AppleScript NSBitmapImageRep AppleScript NSBundle AppleScript NSCFBoolean AppleScript NSCharacterSet AppleScript NSColor AppleScript NSColorList AppleScript NSData AppleScript NSDictionary AppleScript NSError AppleScript NSEvent AppleScript NSFileAttributes AppleScript NSFileManager AppleScript NSFont AppleScript NSFontManager AppleScript NSImage AppleScript NSIndex AppleScript NSKeyedArchiver AppleScript NSKeyedUnarchiver AppleScript NSLocale AppleScript NSMutableArray AppleScript NSMutableDictionary AppleScript NSMutableString AppleScript NSNotFound AppleScript NSNumber AppleScript NSOpenPanel AppleScript NSPasteboard AppleScript NSPDFImageRep AppleScript NSpoint AppleScript NSPredicate AppleScript NSRange AppleScript NSRegularExpression AppleScript NSRunningApplication AppleScript NSScreen AppleScript NSSize AppleScript NSString AppleScript NSStringCompareOptions AppleScript NSTask AppleScript NSTimeZone AppleScript NSURL AppleScript NSURL File AppleScript NSURLBookmark AppleScript NSURLComponents AppleScript NSURLResourceKey AppleScript NSUserDefaults AppleScript NSUUID AppleScript NSView AppleScript NSWorkspace AppleScript Numbers AppleScript OAuth AppleScript ObjC AppleScript OneDrive AppleScript Osax AppleScript PDF AppleScript PDFAnnotationWidget AppleScript PDFContext AppleScript PDFDisplayBox AppleScript PDFDocumentPermissions AppleScript PDFKit AppleScript PDFnUP AppleScript PDFOutline AppleScript Photos AppleScript Photoshop AppleScript Plist System Events AppleScript PostScript AppleScript prefPane AppleScript Preview AppleScript Python AppleScript QR AppleScript QR Decode AppleScript QuickLook AppleScript QuickTime AppleScript record AppleScript Regular Expression AppleScript Reminders AppleScript ReName AppleScript Repeat AppleScript RTF AppleScript Safari AppleScript SaveFile AppleScript ScreenCapture AppleScript ScreenSaver AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript Sort AppleScript Sound AppleScript Spotlight AppleScript SRT AppleScript StandardAdditions AppleScript stringByApplyingTransform AppleScript System Events AppleScript System Settings AppleScript TemporaryItems AppleScript Terminal AppleScript Text AppleScript Text CSV AppleScript Text TSV AppleScript TextEdit AppleScript Translate AppleScript Trash AppleScript Twitter AppleScript UI AppleScript Unit Conversion AppleScript UTType AppleScript valueForKeyPath AppleScript Video AppleScript VisionKit AppleScript Visual Studio Code AppleScript webarchive AppleScript webp AppleScript Wifi AppleScript XML AppleScript XML EPUB AppleScript XML OPML AppleScript XML Plist AppleScript XML RSS AppleScript XML SVG AppleScript XML TTML AppleScript XML webloc AppleScript YouTube AppleScript Zero Suppress Applications Barcode OnLine Tools CityCode Design iPhone List Logs lsappinfo Memo Music perl PlistBuddy pluginkit postalcode ReadMe SF Symbols character id SF Symbols Entity sips Skype Slack sqlite TCC Tools Typography Video Wacom zoom