centenond
centenond

Reputation: 1198

javascript catch errors on function call

In Java methods can use the keyword throws Exception and all errors are thrown when you call the method, this reduce the uses of try catch

I'm learning JavaScript now, but I find hard to believe that there's no similar keyword in JavaScript, are we suppose to surround everything with try-catch blocks?

I find myself checking every variable like this

if(packet.username && packet.password && packet.id && packet.errors)

followed by checking the type of all this vars

and using a lot of try catch blocks which make the code very large and unclear

I find it annoying really, is there a way to handle any errors and catching them in the main function call?

Edit: since it been 3 answers and all of them are misunderstanding the question, sorry about that, English isn't my first language

I don't want to know how to throw an exception, take this java vs javascript example

I'm programming a server which should handle all kinds of errors, now if an error occurs is most certainly a client is sending its own custom data that server don't expect....

In java, I would do something like this

try{
    // I only need to try catch here....
    parsePacket();
}
catch(Exception e){
    e.print();
}

void parsePacket() throws Exception{
    //.....
    // a lot of more possible errors here mainly the ones the server doesn't expect....
    //.....
    anotherFunction();
    //imagine a lot of more functions here that can throw an error
}

void anotherFunction() throws Exception{
    //.....
    // a lot of more posible errors here....
    //.....
}

How pretty? just one try-catch block, however in javascript I find myself doing this

JavaScript

try{

    parsePacket();
}
catch(Exception e){
    e.print();
}

void parsePacket(){
    try{
        //for some reason I have to catch TypeErrors and other ones here too
        //.....
        // a lot of more posible errors
        //.....
        anotherfunction(()=>{
            try{
                //.....
                // a lot of more posible errors here
                //.....
            }
            catch(err){

            }
        })
    }
    catch(err){

    }
}

void anotherFunction(){
    try{
        //.....
        // a lot of more posible errors here
        //.....
    }
    catch(err){

    }
}

And it can get ugly pretty fast

Upvotes: 6

Views: 12023

Answers (4)

Luxknight007
Luxknight007

Reputation: 182

I'm not sure what you are working on, if you are working with nodejs and not limited to importing libraries/packages you could try indicative where in here you can indicate sets of rules to validate your json. Please see reference indicative

const { validate } = require('indicative')

const rules = {
  email: 'required|email|unique:users',
  password: 'required|min:6|max:30'
}

const data = {
  email: '[email protected]',
  password: 'weak'
}

validate(data, rules)
  .then(() => {
  })
  .catch((errors) => {
  })

Upvotes: 1

Any Moose
Any Moose

Reputation: 648

You could use one try and a series of catch aroung the whole script

try {
    if(packet.username && packet.password && packet.id && packet.errors)
    //all the other code
}
catch(err) {
    document.getElementById("error").innerHTML = err.message;
}
} catch (IOException e) {
    e.printStackTrace();
} catch (NumberFormatException e) {
    e.printStackTrace();
}

Upvotes: 0

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21756

In JavaScript, exception handling works bit differently than Java. You need to define your exceptions for each case (type check) and throw that exception if case matches, then that exception will be cached in catch block.

Example of type check from official docs:

function getRectArea(width, height) {
  if (isNaN(width) || isNaN(height)) {
    throw "Parameter is not a number!";
  }
}

try {
  getRectArea(3, 'A');
} catch (e) {
  console.log(e);
  // expected output: "Parameter is not a number!"
}

For more details about throw statement please check here.

I hope this will help you.

Upvotes: 3

Lev Kuznetsov
Lev Kuznetsov

Reputation: 3728

You can throw anything without declaring:

function foo() {
  throw {hello: 'world'}
}

Upvotes: 3

Related Questions