an email address. If the function is successful, it returns the email address as a string.
If it isn’t, it returns an instance of
Error
. For the sake of simplicity, we’ll treat any‐
thing that has an at sign (
@
) in it as a valid email address (see
):
function
validateEmail
(
) {
return
.
match
(
/@/
)
?
:
new
Error(
`invalid email:
${
}
`
);
}
To use this, we can use the
typeof
operator to determine if an instance of
Error
has
been returned. The error message we provided is available in a property
message
:
const
=
;
const
validatedEmail
=
validateEmail
(
);
if
(
validatedEmail
instanceof
Error
) {
console.error(
`Error:
${
validatedEmail
.
message
}
);
} else {
console.log(`
Valid
:
$
{
validatedEmail
}
`);
}
While this is a perfectly valid and useful way to use the
Error
instance, it is more
often used in exception handling, which we’ll cover next.
Exception Handling with try and catch
Exception handling is accomplished with a
try...catch
statement. The idea is that
you “try” things, and if there were any exceptions, they are “caught.” In our previous
example,
validateEmail
handles the anticipated error of someone omitting an at-
sign in their email address, but there is also the possibility of an unanticipated error: a
wayward programmer setting
to something that is not a string. As written, our
previous example setting
to
null
, or a number, or an object—anything but a
string—will cause an error, and your program will halt in a very unfriendly fashion.
To safeguard against this unanticipated error, we can wrap our code in a
try...catch
statement:
const
=
null
;
// whoops
try
{
const
validatedEmail
=
validateEmail
(
);
if
(
validatedEmail
instanceof
Error
) {
console.error(
`Error:
${
validatedEmail
.
message
}
);
} else {
console.log(`
Valid
:
$
{
validatedEmail
}
`);
}
} catch(err) {
console.error(`
Error
:
$
{
err
.
message
}
`);
}
170 | Chapter 11: Exceptions and Error Handling