forked from ErickWendel/high-reliability-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-custom-exception-err.js
38 lines (34 loc) · 941 Bytes
/
02-custom-exception-err.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class InvalidFormatError extends Error {
constructor(message) {
super(message)
this.name = 'InvalidFormatError'
}
}
class InvalidLengthError extends Error {
constructor(message) {
super(message)
this.name = 'InvalidLengthError'
}
}
function validateCpf(cpf) {
if (isNaN(cpf)) {
throw new InvalidFormatError(`O CPF [${cpf}] deve conter apenas numeros`)
}
if (cpf.length !== 11)
throw new InvalidLengthError(`O CPF [${cpf}] deve ter 11 digitos`)
}
for (const cpf of ['123', 'abc', '12345678901']) {
try {
validateCpf(cpf)
console.log(`O CPF [${cpf}] é válido`)
} catch (error) {
if (
error instanceof InvalidFormatError ||
error instanceof InvalidLengthError
) {
console.log(error.message)
continue
}
console.log('Erro desconhecido', error.message)
}
}