4

I'm using define-error to throw custom errors. But it looks like this function wasn't yet implemented in emacs-24.3, for instance.

It still seems to work for emacs-24.3 if I write this:

(when (version< emacs-version "24.4")
  (defun define-error (name message &optional parent)
    "Define NAME as a new error signal.
MESSAGE is a string that will be output to the echo area if such an error
is signaled without being caught by a `condition-case'.
PARENT is either a signal or a list of signals from which it inherits.
Defaults to `error'."
    (unless parent (setq parent 'error))
    (let ((conditions
           (if (consp parent)
               (apply #'nconc
                      (mapcar (lambda (parent)
                                (cons parent
                                      (or (get parent 'error-conditions)
                                          (error "Unknown signal `%s'" parent))))
                              parent))
             (cons parent (get parent 'error-conditions)))))
      (put name 'error-conditions
           (delete-dups (copy-sequence (cons name conditions))))
      (when message (put name 'error-message message)))))

Is this the proper way to get define-error in older Emacs? What was used before it was implemented?

  • 1
    Note that the elisp manual says you shouldn't define missing built-in functions without changing their names: "If a package needs to define an alias or a new function for compatibility with some other version of Emacs, name it with the package prefix, not with the raw name with which it occurs in the other version." So you should define or defalias my-define-error and then use that instead. – sanityinc Nov 26 '14 at 16:51
  • @sanityinc I think it's ok to use an unprefix function, if it's just an exact copy of the original function from the later Emacs release. That won't do no harm, imho. – lunaryorn Nov 26 '14 at 16:53
4

That looks fine, except that I'd use (fboundp 'define-error) instead of testing the version number.

Until Emacs-24.3 what was used instead were manual calls to put as in:

(put 'foo-error 'error-conditions '(foo-error error))
(put 'foo-error 'error-message "Foo on you!")
  • Should I use package prefix for the custom errors that I define? – Yuan Fu Dec 18 '18 at 14:40
  • 1
    @YuanFu: the same risks of naming conflicts exists, so yes, please use a package prefix. – Stefan Dec 18 '18 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.