Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
How to stop a program execution with "throw" in javascript?

I'm resuming javascript studies now and I came across a problem. I have a Customer class that receives customer data in the constructor and validates it before assigning it to its respective properties. When the phone number is incorrect, an exception is thrown which in turn must stop the execution of the entire program, however, this is the problem. I'm throwing the exception and treating it with try/catch but the program continues anyway, here's the code:

// Customer class

import { Library } from './Library.js';
import { books } from './books.js';
import chalk from 'chalk';

export class Customer {
    #name;
    #birthdate;
    #email;
    #phone;
    #code;

    constructor(name, birthdate, email, phone) {
        this.#name = name;
        this.#birthdate = birthdate;
        this.#email = email;
        this.#phone = this.#validatePhone(phone);
        this.rented = [];
        this.#code = Math.trunc(Math.random() * 99999); // MUST BE READABLE, ONLY!
    }

    get name() {
        return this.#name;
    }

    get birthdate() {
        return this.#birthdate;
    }

    get email() {
        return this.#email;
    }

    get phone() {
        return this.#phone;
    }

    set name(name) {
        this.#name = name;
    }

    set birthdate(birthdate) {
        this.#birthdate = birthdate;
    }

    set email(email) {
        this.#email = email;
    }

    set phone(phone) {
        this.#phone = phone;
    }

    async rentBoook(title, days) {
        const search = await Library.searchBook(title);
        if(search.length === 0) throw 'This book doesn\'t exist!';

        return await Library.rentBook('O Ar', this, days);
    }

    #validatePhone(phone) {
        try {
            const pattern = /(\(?[0-9]{2}\)?)\s?([0-9]{5})-?([0-9]{4})/;
            if(!pattern.test(phone)) throw 'Invalid phone number!';

            return phone;
        }catch(err) {
            console.log(chalk.red(err));
        }

    }
}
   // Index

    import chalk from 'chalk';
    import { Customer } from './Customer.js';

    const customer = new Customer('John Doe', '20-04-04', 'r@r.com', '(99) 9999-99999');

    customer.rentBoook('O Ar', 7)
    .then(r => console.log(chalk.green('Book rented with success!')))
    .catch(err => console.log(chalk.red(err)));
    // Output

    "Invalid phone number!"
    "Book rented with success!"
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Phone validation should be handled in rentBook method, as validation didn't handled inside the rentBook & happened for #phone prop assignment (#phone will become undefined), both the method execute independent of one another.

For this case, will get expected result, when validation done inside rentBook before Library.search

async rentBoook(title, days) {
       ....
       validatePhone()
       ...
}

remove try catch in validatePhone Method & use try..catch in rentBook if needed

Hope this helps

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda