Skip to main content

type-error-datum, type-error-expected-type

type-error-datum, type-error-expected-type Function

Syntax:

type-error-datum condition → datum

type-error-expected-type condition → expected-type

Arguments and Values:

condition—a condition of type type-error.

datum—an object.

expected-type—a type specifier .

Description:

type-error-datum returns the offending datum in the situation represented by the condition.

type-error-expected-type returns the expected type of the offending datum in the situation represented by the condition.

Examples:

(defun fix-digits (condition) 
(check-type condition type-error)
(let\* ((digits(zero one two three four
five six seven eight nine))
(val (position (type-error-datum condition) digits)))
(if (and val (subtypep ’fixnum (type-error-expected-type condition)))
(store-value 7))))
(defun foo (x)
(handler-bind ((type-error #’fix-digits))
(check-type x number)
(+ x 3)))
(foo ’seven)
10

See Also:

type-error, Chapter 9 (Conditions)

Expanded Reference: type-error-datum, type-error-expected-type

Extracting Information from a type-error

type-error-datum returns the offending object, and type-error-expected-type returns the type that was expected.

(let ((x nil))
(handler-case
(check-type x string)
(type-error (c)
(values (type-error-datum c)
(type-error-expected-type c)))))
=> NIL
=> STRING

Using Both Accessors for Error Reporting

(defun safe-char (x)
(handler-case
(coerce x 'character)
(type-error (c)
(format nil "Cannot coerce ~S to ~A"
(type-error-datum c)
(type-error-expected-type c)))))
=> SAFE-CHAR

(safe-char "hello")
=> "Cannot coerce \"hello\" to (OR CHARACTER (STRING 1))"

With Manually Signaled Errors

(handler-case
(error 'type-error :datum 42 :expected-type 'string)
(type-error (c)
(list :datum (type-error-datum c)
:expected (type-error-expected-type c))))
=> (:DATUM 42 :EXPECTED STRING)