NSError

[Error]MacErrors.hの内容をplistにしてエラー番号から内容を検索する


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(* com.cocolog-nifty.quicktimer.icefloe
004MacErrors.hの値を参照します
005参照検索用に
006/Users/ユーザー名/Documents/Apple/MacErrors/MacErrors.plist
007
008作成します
009*)
010----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
011use AppleScript version "2.8"
012use framework "Foundation"
013use framework "AppKit"
014use framework "CoreServices"
015use scripting additions
016property refNSNotFound : a reference to 9.22337203685477E+18 + 5807
017property refMe : a reference to current application
018
019set strMes to ("エラー番号を半角数字で入力\rマイナスの場合はマイナス記号が必要です") as text
020
021########################
022## クリップボードの中身取り出し
023########################
024###初期化
025set appPasteboard to refMe's NSPasteboard's generalPasteboard()
026##格納されているタイプをリストにして
027set ocidPastBoardTypeArray to appPasteboard's types
028###テキストがあれば
029set boolContain to ocidPastBoardTypeArray's containsObject:("public.utf8-plain-text")
030if (boolContain as boolean) is true then
031  ###値を格納する
032  tell application "Finder"
033    set strReadString to (the clipboard as text) as text
034  end tell
035else
036  ###UTF8が無いなら
037  ##テキスト形式があるか?確認して
038  set boolContain to ocidPastBoardTypeArray's containsObject:(refMe's NSPasteboardTypeString)
039  ##テキスト形式があるなら
040  if (boolContain as boolean) is true then
041    set ocidTypeClassArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
042    ocidTypeClassArray's addObject:(refMe's NSString)
043    set ocidReadString to appPasteboard's readObjectsForClasses:(ocidTypeClassArray) options:(missing value)
044    set strReadString to ocidReadString as text
045  else
046    log "テキストなし"
047    set strReadString to strMes as text
048  end if
049end if
050##############################
051#####ダイアログ
052##############################
053set boolCalculator to (missing value)
054###ダイアログを前面に出す
055set strName to (name of current application) as text
056if strName is "osascript" then
057  tell application "Finder" to activate
058else
059  tell current application to activate
060end if
061set aliasIconPath to POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns" as alias
062try
063  set recordResult to (display dialog strMes with title "入力してください" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" with icon aliasIconPath giving up after 20 without hidden answer) as record
064on error
065  log "エラーしました"
066  return
067end try
068if "OK" is equal to (button returned of recordResult) then
069  set strReturnedText to (text returned of recordResult) as text
070else if (gave up of recordResult) is true then
071  return "時間切れです"
072else
073  return "キャンセル"
074end if
075##############################
076#####戻り値整形
077##############################
078set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
079set ocidResponseText to (ocidResponseText's stringByReplacingOccurrencesOfString:("\t") withString:(""))
080set ocidResponseText to (ocidResponseText's stringByReplacingOccurrencesOfString:("\n") withString:(""))
081set ocidResponseText to (ocidResponseText's stringByReplacingOccurrencesOfString:("\r") withString:(""))
082
083####戻り値を半角にする
084set ocidNSStringTransform to (refMe's NSStringTransformFullwidthToHalfwidth)
085set ocidTextM to (ocidResponseText's stringByApplyingTransform:ocidNSStringTransform |reverse|:false)
086
087###数字以外があれば中止する
088set ocidDemSet to refMe's NSCharacterSet's characterSetWithCharactersInString:("0123456789-")
089##数字以外って意味で逆セット
090set ocidCharSet to ocidDemSet's invertedSet()
091set ocidOption to (refMe's NSLiteralSearch)
092##数字以外の文字を探して
093set ocidRange to ocidResponseText's rangeOfCharacterFromSet:(ocidCharSet) options:(ocidOption)
094set ocidLocation to ocidRange's location
095##なければOK
096if ocidLocation = refNSNotFound then
097  log "処理開始"
098else if ocidLocation  0 then
099  tell application "Finder"
100    set aliasPathToMe to (path to me) as alias
101  end tell
102  log "数値以外の値があったのでやりなし"
103  return run script aliasPathToMe
104end if
105#これが検索語句
106set strErrorNo to ocidTextM as string
107
108################
109#パス
110set strSubPathH to ("/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CarbonCore.framework/Versions/A/Headers/MacErrors.h") as text
111set strSubPathR to ("/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CarbonCore.framework/Versions/A/Headers/MacErrors.r") as text
112
113#ベースパス
114set strXcodePath to ("/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk")
115set strCmmandToolPath to ("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk")
116
117################
118#Xcode
119set strFilePath to (strXcodePath & strSubPathH) as text
120set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
121set ocidFilePathR to ocidFilePathStr's stringByStandardizingPath()
122#有無チェック
123set appFileManager to refMe's NSFileManager's defaultManager()
124set boolDirExists to appFileManager's fileExistsAtPath:(ocidFilePathR) isDirectory:(false)
125#Xcodeインストール済みならこちらのパス
126if boolDirExists = true then
127  set ocidFilePath to ocidFilePathR
128else if boolDirExists = false then
129  #CommandLineTools
130  set strFilePath to (strCmmandToolPath & strSubPathH) as text
131  set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
132  set ocidFilePathR to ocidFilePathStr's stringByStandardizingPath()
133  #有無チェック
134  set boolDirExists to appFileManager's fileExistsAtPath:(ocidFilePathR) isDirectory:(false)
135  if boolDirExists = true then
136    set ocidFilePath to ocidFilePathR
137  else if boolDirExists = false then
138    set strAlertMes to ("ファイルが見つかりません\rXcodeかCommandLineToolsを\rインストールしてください") as text
139    display alert strAlertMes buttons {"終了"} default button "終了" cancel button "終了" as informational giving up after 10
140    return
141  end if
142end if
143#使用するパス
144set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
145
146################
147#Plistの保存先
148set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDocumentDirectory) inDomains:(refMe's NSUserDomainMask))
149set ocidDocumentDirPathURL to ocidURLsArray's firstObject()
150set ocidSaveDirPathURL to ocidDocumentDirPathURL's URLByAppendingPathComponent:("Apple/MacErrors") isDirectory:(true)
151#フォルダを作る
152set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
153ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
154set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:(true) attributes:(ocidAttrDict) |error| :(reference)
155#PLISTパス
156set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("MacErrors.plist") isDirectory:(false)
157################################
158#初回チェック
159set ocidSaveFilePath to ocidSaveFilePathURL's |path|()
160set boolDirExists to appFileManager's fileExistsAtPath:(ocidSaveFilePath) isDirectory:(true)
161if boolDirExists = true then
162  #すでにあるので作成しない
163  set ocidPlistArray to refMe's NSMutableArray's alloc()'s initWithContentsOfURL:(ocidSaveFilePathURL)
164else if boolDirExists = false then
165  #PLISTを作成する
166  set ocidPlistArray to doMakePlist(ocidFilePathURL, ocidSaveFilePathURL)
167end if
168
169################################
170#検索
171set numCntArray to ocidPlistArray's |count|()
172#出力用のテキスト
173set ocidOutputString to refMe's NSMutableString's alloc()'s init()
174
175#
176repeat with itemNo from 0 to (numCntArray - 1) by 1
177  #順番に取り出して
178  set ocidItemDict to (ocidPlistArray's objectAtIndex:(itemNo))
179  #
180  set ocidValueArray to (ocidItemDict's objectForKey:(strErrorNo))
181  if ocidValueArray  (missing value) then
182    (ocidOutputString's appendString:("ErrorNo: "))
183    (ocidOutputString's appendString:(strErrorNo))
184    (ocidOutputString's appendString:("\n"))
185    (ocidOutputString's appendString:("ErrorCode: "))
186    (ocidOutputString's appendString:(ocidValueArray's firstObject()))
187    (ocidOutputString's appendString:("\n"))
188    (ocidOutputString's appendString:("Info: "))
189    (ocidOutputString's appendString:(ocidValueArray's lastObject()))
190    (ocidOutputString's appendString:("\n"))
191  end if
192  
193end repeat
194
195################################
196#NSErrorの値も入れる
197set ocidNSErrorData to refMe's NSError's errorWithDomain:(refMe's NSCocoaErrorDomain) code:(strErrorNo) userInfo:(missing value)
198set ocidDiscription to ocidNSErrorData's localizedDescription() as text
199(ocidOutputString's appendString:("Description: "))
200(ocidOutputString's appendString:(ocidDiscription))
201(ocidOutputString's appendString:("\n"))
202
203set strMes to ocidOutputString as text
204
205##############################
206#####ダイアログ
207##############################
208tell current application
209  set strName to name as text
210end tell
211####スクリプトメニューから実行したら
212if strName is "osascript" then
213  tell application "Finder"
214    activate
215  end tell
216else
217  tell current application
218    activate
219  end tell
220end if
221try
222  set recordResult to (display dialog strMes with title "戻り値です" default answer strMes buttons {"クリップボードにコピー", "終了", "再実行"} default button "再実行" cancel button "終了" giving up after 20 with icon aliasIconPath without hidden answer) as record
223on error
224  return "エラーしました"
225end try
226if (gave up of recordResult) is true then
227  return "時間切れです"
228end if
229##############################
230#####自分自身を再実行
231##############################
232if button returned of recordResult is "再実行" then
233  tell application "Finder"
234    set aliasPathToMe to (path to me) as alias
235  end tell
236  run script aliasPathToMe with parameters "再実行"
237  return
238end if
239##############################
240#####値のコピー
241##############################
242if button returned of recordResult is "クリップボードにコピー" then
243  try
244    set strText to text returned of recordResult as text
245    ####ペーストボード宣言
246    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
247    set ocidText to (refMe's NSString's stringWithString:(strText))
248    appPasteboard's clearContents()
249    appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
250  on error
251    tell application "Finder"
252      set the clipboard to strText as text
253    end tell
254  end try
255end if
256
257
258
259
260################################
261#PLIST作成
262to doMakePlist(ocidFilePathURL, ocidSaveFilePathURL)
263  #作成する
264  ################
265  #ファイル読み込み
266  set listResponse to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference)
267  set ocidReadStrings to (item 1 of listResponse)
268  #UTF8でエラーならASCIIにする
269  if ocidReadStrings = (missing value) then
270    set listResponse to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSASCIIStringEncoding) |error| :(reference)
271    set ocidReadStrings to (item 1 of listResponse)
272  end if
273  #Arrayに
274  set ocidLineArray to ocidReadStrings's componentsSeparatedByString:("\n")
275  #次の工程に回すARRAY
276  set ocidRootArray to refMe's NSMutableArray's alloc()'s init()
277  #各行順処理
278  repeat with itemLine in ocidLineArray
279    #行判定
280    set boolStart to (itemLine's hasPrefix:("enum"))
281    set boolEnd to (itemLine's hasPrefix:("};"))
282    set boolContain to (itemLine's containsString:("="))
283    #判定別処理
284    if boolStart is true then
285      set ocidSubArray to refMe's NSMutableArray's alloc()'s init()
286    else if boolEnd is true then
287      (ocidRootArray's addObject:(ocidSubArray))
288    else if boolContain is true then
289      (ocidSubArray's addObject:(itemLine))
290    end if
291  end repeat
292  
293  ################
294  #2時工程
295  set numCntArray to ocidRootArray's |count|()
296  #出力用のARRAY これをPLISTにする
297  set ocidPlistArray to refMe's NSMutableArray's alloc()'s init()
298  #ここで正規表現初期化
299  set strRegpattern to ("(?<=/\\*)\\s*(.*?)\\s*(?=\\*/)") as text
300  set listResponse to refMe's NSRegularExpression's regularExpressionWithPattern:(strRegpattern) options:(0) |error| :(reference)
301  set appRegA to (item 1 of listResponse)
302  #
303  set strRegpattern to ("^\\s*(-?\\d+)(?!=\\,)") as text
304  set listResponse to refMe's NSRegularExpression's regularExpressionWithPattern:(strRegpattern) options:(0) |error| :(reference)
305  set appRegB to (item 1 of listResponse)
306  
307  #順番に処理
308  repeat with itemNo from 0 to (numCntArray - 1) by 1
309    #行内容のDICT と Array
310    set ocidItemDict to refMe's NSMutableDictionary's alloc()'s init()
311    #ARRAY取り出し
312    set ocidLineArray to (ocidRootArray's objectAtIndex:(itemNo))
313    repeat with itemLineArray in ocidLineArray
314      #=で前後に分けて
315      set ociditemLineSubArray to (itemLineArray's componentsSeparatedByString:("="))
316      #エラー名
317      set ocidErroeName to ociditemLineSubArray's firstObject()
318      set ocidErroeName to (ocidErroeName's stringByReplacingOccurrencesOfString:(" ") withString:(""))
319      #エラー番号と コメント
320      set ocidErroeNoStr to ociditemLineSubArray's lastObject()
321      #正規表現 エラーメッセージ
322      set ocidLength to ocidErroeNoStr's |length|()
323      set ocidRange to refMe's NSRange's NSMakeRange(0, ocidLength)
324      set ocidMatch to (appRegA's firstMatchInString:(ocidErroeNoStr) options:(0) range:(ocidRange))
325      if ocidMatch = (missing value) then
326        set ocidErrorMes to ("") as text
327      else
328        set ocidErrorMes to (ocidErroeNoStr's substringWithRange:(ocidMatch's range()))
329      end if
330      #正規表現 エラー番号
331      set ocidMatch to (appRegB's firstMatchInString:(ocidErroeNoStr) options:(0) range:(ocidRange))
332      if ocidMatch = (missing value) then
333        set ocidErrorMes to ("") as text
334      else
335        set ocidErrorNO to (ocidErroeNoStr's substringWithRange:(ocidMatch's range()))
336        set ocidErrorNO to (ocidErrorNO's stringByReplacingOccurrencesOfString:(" ") withString:(""))
337        set ocidErrorNO to (ocidErrorNO's stringByReplacingOccurrencesOfString:("\t") withString:(""))
338        #
339        set ocidItemLineArray to refMe's NSMutableArray's alloc()'s init()
340        (ocidItemLineArray's addObject:(ocidErroeName))
341        (ocidItemLineArray's addObject:(ocidErrorMes))
342        #
343        (ocidItemDict's setObject:(ocidItemLineArray) forKey:(ocidErrorNO))
344      end if
345      
346    end repeat
347    (ocidPlistArray's addObject:(ocidItemDict))
348    
349  end repeat
350  
351  ################
352  #とりあえず保存しておく
353  set ocidFormat to (current application's NSPropertyListBinaryFormat_v1_0)
354  set listResponse to current application's NSPropertyListSerialization's dataWithPropertyList:(ocidPlistArray) format:(ocidFormat) options:0  |error| :(reference)
355  if (item 2 of listResponse) = (missing value) then
356    set ocidPlistData to (item 1 of listResponse)
357  else if (item 2 of listResponse) (missing value) then
358    set strErrorNo to (item 2 of listResponse)'s code() as text
359    set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
360    current application's NSLog("■:" & strErrorNo & strErrorMes)
361    return "エラーしました" & strErrorNo & strErrorMes
362  end if
363  
364  #保存 
365  set ocidOption to (current application's NSDataWritingAtomic)
366  set listDone to ocidPlistData's writeToURL:(ocidSaveFilePathURL) options:(ocidOption) |error| :(reference)
367  if (item 1 of listDone) is true then
368    log "正常終了"
369  else if (item 1 of listDone) is false then
370    set strErrorNo to (item 2 of listResponse)'s code() as text
371    set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text
372    current application's NSLog("■:" & strErrorNo & strErrorMes)
373    return "エラーしました" & strErrorNo & strErrorMes
374  end if
375  return ocidPlistArray
376end doMakePlist
377
AppleScriptで生成しました

|

[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

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat 2024 Acrobat AddOn Acrobat Annotation Acrobat AppleScript Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat GentechAI Acrobat JS Acrobat JS Word Search Acrobat Maintenance Acrobat Manifest Acrobat Menu Acrobat Merge Acrobat Open Acrobat PDFPage Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Print Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat Registered Products Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat URL List Mac Acrobat URL List Windows Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin ConfigCode Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin NetWork Admin Permission Admin Pkg Admin Power Management Admin Printer Admin Printer Basic Admin Printer Custompapers Admin SetUp Admin SMB Admin softwareupdate Admin Support Admin System Information Admin TCC Admin Tools Admin Umask Admin Users Admin Volumes Admin XProtect Adobe Adobe AUSST Adobe Bridge Adobe Documents Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager Adobe Sap Code AppKit Apple AppleScript AppleScript Duplicate AppleScript entire contents AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Video Applications AppStore Archive Archive Keka Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome Chromedriver CIImage CityCode CloudStorage Color Color NSColor Color NSColorList com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Desktop Position Device Diff Disk do shell script Dock Dock Launchpad DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData exiftool ffmpeg File File Name Finder Finder Window Firefox Folder FolderAction Font List FontCollections Fonts Fonts Asset_Font Fonts ATS Fonts Emoji Fonts Maintenance Fonts Morisawa Fonts Python Fonts Variable Foxit GIF github Guide HTML Icon Icon Assets.car Illustrator Image Events ImageOptim Input Dictionary iPhone iWork Javascript Jedit Ω Json Label Language Link locationd lsappinfo m3u8 Mail Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Microsoft Fonts Microsoft Office Microsoft Office Link Microsoft OneDrive Microsoft Teams Mouse Music Node Notes NSArray NSArray Sort NSAttributedString NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSGraphicsContext Crop NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSet NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSUbiquitous NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth PDF PDF Image2PDF PDF MakePDF PDF nUP PDF Pymupdf PDF Pypdf PDFContext PDFDisplayBox PDFImageRep PDFKit PDFKit Annotation PDFKit AnnotationWidget PDFKit DocumentPermissions PDFKit OCR PDFKit Outline PDFKit Start PDFPage PDFPage Rotation PDFView perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript PowerShell prefPane Preview Python Python eyed3 Python pip QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver Script Editor Script Menu SF Symbols character id SF Symbols Entity Shortcuts Shortcuts Events sips Skype Slack Sound Spotlight sqlite StandardAdditions StationSearch Subtitles LRC Subtitles SRT Subtitles VTT Swift swiftDialog System Events System Settings TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code VMware Fusion Wacom Weather webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML LSSharedFileList sfl2 XML LSSharedFileList sfl3 XML objectsForXQuery XML OPML XML Plist XML Plist System Events XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube Zero Padding zoom