AppleScript NSError

[AppleScript]ドロップレット OPENしたくない(Openに値を渡さない & ログを出す)その2


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#! /usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# com.cocolog-nifty.quicktimer.icefloe
004#
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use scripting additions
009
010property refMe : a reference to current application
011
012###################
013#Wクリックで実行
014#エディタから実行
015on run
016  
017  set listAliasFilePath to (choose file with multiple selections allowed) as list
018  #サブルーチンに渡す
019  set boolDone to doAction(listAliasFilePath)
020  if boolDone is false then
021    display alert "エラーが発生しました" message "エラーが発生しました"
022    return
023  end if
024  return
025  
026end run
027
028###################
029#ドロップ
030on open listAliasFilePath
031  #サブルーチンに渡す
032  set boolDone to doAction(listAliasFilePath)
033  if boolDone is false then
034    display alert "エラーが発生しました" message "エラーが発生しました"
035    return
036  end if
037  return
038  
039end open
040
041###################
042#実行されるのはこれ
043to doAction(argListAliasFilePath)
044  #ファイルエイリアスリストを順番の処理
045  repeat with itemAliasFilePath in argListAliasFilePath
046    try
047      ##ここに本処理
048      set listButtons to {"OK", "QUIT"} as list
049      display alert "ドロップしたファイルのパス" message (itemAliasFilePath as text) buttons listButtons default button (item 1 of listButtons) cancel button (item 2 of listButtons) giving up after 3
050    on error
051      #エラーをログにする
052      refMe's NSLog("■■■: サブルーチンでエラーになりました")
053      return false
054    end try
055  end repeat
056  #全部エラーなく終わったらtrueを戻す
057  return true
058end doAction
AppleScriptで生成しました

|

[NSError]エラーで停止する(普段使い用)


あくまでも参考にしてください

サンプルソース(参考)
行番号ソース
001set appFileManager to refMe's NSFileManager's defaultManager()
002set listDone to (appFileManager's moveItemAtURL:(ocidFilePathURL) toURL:(ocidSaveFilePathURL) |error| :(reference))
003
004if (item 1 of listDone) is true then
005  log "正常処理"
006else if (item 2 of listDone) ≠ (missing value) then
007  log (item 2 of listDone)'s code() as text
008  log (item 2 of listDone)'s localizedDescription() as text
009  return "エラーしました"
010end if
AppleScriptで生成しました

あくまでも参考にしてください

サンプルソース(参考)
行番号ソース
001set ocidOption to (refMe's NSDataReadingMappedIfSafe)
002set listResponse to refMe's NSImage's alloc()'s initWithContentsOfURL:(ocidFilePathURL) options:(ocidOption) |error| :(reference)
003
004if (item 2 of listResponse) = (missing value) then
005  log "正常処理"
006  set ocidXXXXX to (item 1 of listResponse)
007else if (item 2 of listResponse) ≠ (missing value) then
008  log (item 2 of listResponse)'s code() as text
009  log (item 2 of listResponse)'s localizedDescription() as text
010  return "エラーしました"
011end if
AppleScriptで生成しました

あくまでも参考にしてください

サンプルソース(参考)
行番号ソース
001set ocidKey to (refMe's NSURLIsDirectoryKey)
002set listResponse to ocidFilePathURL's getResourceValue:(reference) forKey:(ocidKey) |error| :(reference)
003if (item 1 of listResponse) is true then
004  log "正常処理"
005  set ocidXXXXX to (item 2 of listResponse)
006else if (item 3 of listResponse) ≠ (missing value) then
007  log (item 3 of listResponse)'s code() as text
008  log (item 3 of listResponse)'s localizedDescription() as text
009  return "エラーしました"
010end if
AppleScriptで生成しました

あくまでも参考にしてください

サンプルソース(参考)
行番号ソース
001tell application "SOME App"
002  set appFileManager to refMe's NSFileManager's defaultManager()
003  set listDone to (appFileManager's moveItemAtURL:(ocidFilePathURL) toURL:(ocidSaveFilePathURL) |error| :(specifier))
004  if (item 1 of listDone) is true then
005    log "リネームしました"
006  else if (item 2 of listDone) ≠ (missing value) then
007    log (item 2 of listDone)'s code() as text
008    log (item 2 of listDone)'s localizedDescription() as text
009    return "エラーしました"
010  end if
011end tell
AppleScriptで生成しました

|

[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 2020 Acrobat AddOn Acrobat Annotation Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat python Acrobat Reader Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Adobe Adobe FDKO Adobe RemoteUpdateManager Apple AppleScript AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes AppleScript Audio 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 Diff AppleScript Disk AppleScript do shell script AppleScript Dock AppleScript DropBox AppleScript Droplet AppleScript eMail AppleScript Encode % AppleScript Encode Decode AppleScript Encode UTF8 AppleScript Error AppleScript EXIFData AppleScript ffmpeg AppleScript File AppleScript Finder AppleScript Firefox AppleScript Folder AppleScript Fonts AppleScript GIF AppleScript Guide AppleScript HTML AppleScript HTML Entity AppleScript Icon AppleScript Illustrator AppleScript Image Events AppleScript Image2PDF AppleScript ImageOptim AppleScript iWork AppleScript Javascript AppleScript Jedit AppleScript Json AppleScript Label AppleScript Leading Zero AppleScript List AppleScript locationd AppleScript LRC AppleScript LSSharedFileList AppleScript m3u8 AppleScript Mail AppleScript MakePDF AppleScript Map AppleScript Math AppleScript Messages AppleScript Microsoft AppleScript Microsoft Edge AppleScript Microsoft Excel AppleScript Mouse AppleScript Movie AppleScript Music AppleScript NetWork AppleScript Notes AppleScript NSArray AppleScript NSArray Sort 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 NSFileManager enumeratorAtURL AppleScript NSFont AppleScript NSFontManager AppleScript NSGraphicsContext 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 NSpoint AppleScript NSPredicate AppleScript NSPrintOperation AppleScript NSRange AppleScript NSRect 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 NSURLSession AppleScript NSUserDefaults AppleScript NSUUID AppleScript NSView AppleScript NSWorkspace AppleScript Numbers AppleScript OAuth AppleScript ObjC AppleScript OneDrive AppleScript Osax AppleScript PDF AppleScript PDFAnnotation AppleScript PDFAnnotationWidget AppleScript PDFContext AppleScript PDFDisplayBox AppleScript PDFDocumentPermissions AppleScript PDFImageRep AppleScript PDFKit AppleScript PDFnUP AppleScript PDFOutline AppleScript Photoshop AppleScript Pictures 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 Sound AppleScript Spotlight AppleScript SRT AppleScript StandardAdditions AppleScript stringByApplyingTransform AppleScript Swift AppleScript System Events AppleScript System Events Plist AppleScript System Settings AppleScript TemporaryItems AppleScript Terminal AppleScript Text AppleScript Text CSV AppleScript Text MD 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 savedSearch AppleScript XML SVG AppleScript XML TTML AppleScript XML webloc AppleScript XMP AppleScript YouTube Applications CityCode github iPhone List lsappinfo Memo Music perl PlistBuddy pluginkit postalcode ReadMe SF Symbols character id SF Symbols Entity sips Skype Slack sqlite TCC Tools Typography Video Wacom Windows zoom