anonymous@RULINUX.NET~# Last login: 2025-03-16 08:11:07
Регистрация Вход Новости | Разметка | Пользователи | Галерея | Форум | Статьи | Неподтвержденное | Трекер | Правила форума | F.A.Q. | Ссылки | Поиск


Re:Exception

Заменять exception на NULL -- явно неудачная идея.

Вот как я отлавливаю ошибки в своем загрузчике картинок с голыми девками с борд:

lisp

(defun download-images% (uri directory)
  "Download images from a thread (without error handling)"
  (with-simple-restart (thread-skip "Skip downloading this thread")
    (let* ((thread (make-thread uri))
           (pathname (get-directory-pathname directory (directory-name thread))))
      (let ((files (remove-extensions (image-sources thread) *ignored-extensions*)))
        (ensure-directories-exist pathname)
        (format t "Downloading total of ~d images~%" (length files))
        (mapc (lambda (file)
                (format t ".")
                (force-output)
                (destructuring-bind (uri . name) file
                  (let ((file-path (merge-pathnames name pathname)))
                    (tagbody retry
                       (restart-case
                           (if (not (open file-path :direction :probe))
                               (let ((data (make-request uri)))
                                 (with-open-file (output file-path
                                                         :direction :output
                                                         :if-does-not-exist :create
                                                         :element-type '(unsigned-byte 8))
                                   (write-sequence data output))))
                         (file-skip ()
                           :report "Skip downloading file" ())
                         (file-retry ()
                           :report "Retry downloading file" (go retry)))))))
              files))))
  (format t "~%")
  t)

(defun try-restarts (restarts)
  "Invoke the first available restart from list"
  (mapc (lambda (restart)
          (if (find-restart restart)
              (invoke-restart restart)))
        restarts))

(defun handle-conditions (condition)
  "Handle conditions automatically or fall back to the debugger"
  (princ condition *error-output*)
  (terpri *error-output*)
  (force-output *error-output*)
  (typecase condition
    (unknown-resource
     ;; Skip the thread and continue with a new one
     (invoke-restart 'thread-skip))
    ((or bad-response-code usocket:timeout-error)
     ;; Try to skip a file first
     (try-restarts '(file-skip thread-skip)))))

(defun download-images (uri directory)
  "Download images from a thread. URI is a desired resource WWW address.
 All files will be saved to DIRECTORY + some guessed name, based on the
 name of the thread or URI."

  (handler-bind
      (((or file-error usocket:socket-error
            image-downloader-error)
        #'handle-conditions))
    (download-images% uri directory)))
 


Ошибки возникают внутри make-request (тут не показано) при невозможности скачать картинку. Далее, даунлоадер предоставляет стратегии исправления ошибок (пропуск треда, пропуск файла, повтор попытки). handle-conditions выбирает нужную стратегию в зависимости от ошибки (выбрать один из рестартов или вывалиться в интерактивный отладчик), а также печатает какую-либо осмысленную инфу об ошибке. Наконец, в download-images мы связываем обработчик ошибок handle-conditions с функцией скачивания.

Если заменять condition на простое значение (NULL), теряется весь смысл какого-то особого мехазизма обработки ошибок. Получается что-то в роде C с кодами ошибок

Vasily(*)(2018-03-19 09:10:33)

Mozilla/5.0 (X11; FreeBSD) AppleWebKit/602.1 (KHTML, like Gecko) QupZilla/1.8.9 Version/9.0 Safari/602.1
Тема:

Ваш комментарий:

Выберите фильтр: матерные выражения
торсионщина
нацпол
спам
флуд
порно
изображения
модераторские/пользовательские фильтры
captcha
Введите символы либо ответ (если на картинке задача):

Пользователям браузеров без CSS: Поле для проверки, заполнять НЕ НАДО:




(c) 2010-2020 LOR-NG Developers Group
Powered by TimeMachine

Valid HTML 4.01 Transitional Правильный CSS!