LEARNING JAVASCRIPT - Trang 194

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

Chapter 17

):

function

validateEmail

(

email

) {

return

email

.

match

(

/@/

)

?

email

:

new

Error(

`invalid email:

${

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

email

=

"[email protected]"

;

const

validatedEmail

=

validateEmail

(

email

);

if

(

validatedEmail

instanceof

Error

) {

console.error(

`Error:

${

validatedEmail

.

message

}

);

} else {
console.log(`

Valid

email

:

$

{

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

email

to something that is not a string. As written, our

previous example setting

email

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

email

=

null

;

// whoops

try

{

const

validatedEmail

=

validateEmail

(

email

);

if

(

validatedEmail

instanceof

Error

) {

console.error(

`Error:

${

validatedEmail

.

message

}

);

} else {
console.log(`

Valid

email

:

$

{

validatedEmail

}

`);

}
} catch(err) {
console.error(`

Error

:

$

{

err

.

message

}

`);

}

170 | Chapter 11: Exceptions and Error Handling

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.