3
It is common to have mistakes thrown and these errors have to be captured and treated in different ways, according to the context. I see (and use) the practice of creating custom classes of errors (which I will still ask a specific question on the subject), such as (self-explanatory):
export class InternalServerException extends Error{
...
}
export class APIResponseException extends Error{
...
}
export class DataBaseConnectionException extends Error{
...
}
Error handling done always inside the block catch
, but with the use of if
s to perform a particular operation according to the error instance:
try {
...
executaAlgumaCoisa()
...
} catch (error) {
if (error instanceof APIResponseException) {
// trata para o erro de API
}
if (error instanceof InternalServerException) {
// trata para o erro interno
}
}
What sucks about all this is doing if
s and still have to import these classes only for instance checking and know where the error comes from, whether it is from the API or internal application error, where these classes are the causes(cause) errors, in order to be able to perform actions according to.
Any example, executable to demonstrate:
class NumeroParError extends Error {
constructor(message) {
super(message)
this.name = 'Error de Par'
}
}
class NumeroImparError extends Error {
constructor(message) {
super(message)
this.name = 'Error de Ímpar'
}
}
try {
const numero = Math.floor(Math.random() * 10)
if (numero % 2) {
throw new NumeroImparError(numero)
} else {
throw new NumeroParError(numero)
}
} catch (err) {
if (err instanceof NumeroParError) {
console.log(`${err.name}. Motivo: ${err.message}`)
}
if (err instanceof NumeroImparError) {
console.log(`${err.name}. Motivo: ${err.message}`)
}
}
The new Javascript feature called Error causes
has come to give greater semantics to bug objects and minimize the amount of code to be written.
- How this feature works?
- It will be useful to the point of not having to create custom error classes like
InternalServerException
andAPIResponseException
?