简体   繁体   中英

Javascript throw vs. return error object vs. callback

I'm writing an assembler and simulator for a toy assembly language that I have my CS students use in class. I'm writing it in javascript with the idea that I could then build a simple UI in the browser which would show students how each instruction changes the state of the machine and such.

One question that I'm grappling with is the best way to return error information from the assembler when invalid assembly code is passed. The assembler has an extremely simple API at the moment:

var assembler = ... // Get the assembler object
var valid_source = "0 mov r1 r2\n1 halt";
var valid_binary = assembler.assemble(valid_source);  // String containing 0's and 1's

var invalid_source = "foo bar baz!";
var invalid_binary = assembler.assemble(invalid_source); // What should happen here?

I have a few thoughts about how this might work:

  1. Construct and throw a new javascript Error object. This seems like overkill (and ultimately maybe not even helpful since the user wouldn't care about the javascript stacktrace, etc).
  2. Return a string or object containing error information. Then the user of the assembler gets to make the choice about what to do with errors (if anything).
  3. Change the assembler API to use a callback instead:

    assembler.assemble(source, function(binary, error) { if (error) { // Handle the error } // Otherwise, do stuff with the binary });

  4. Something else entirely?

Any ideas, thoughts, or feedback would be much appreciated.

I think your three options would work fine. Now from my perspective:

I would keep away from the third option because it gives the feeling it is an async function when it is not.

I would go for option 1 or 2. The first one is a little overkill but I think it is the most realistic approach to what compilers do. Exit with no zero code. But then you would need to add a try/catch block to handle the error.

So the next option is to return an error object. Seems the best option for me.

I recommend you to return an Error object. It is as simple as:

return new Error('Parsing error');

// Or with an error name
var error = new Error('Parsing error');
error.name = 'PARSING_ERROR';
return error;

One advantage to use the error object is that it gives you the stack trace and other handy stuff. More info here .

Also, to check if there was any error just need to check the variable type:

if (typeof valid_binary === 'string') { /* no error */ }

// Or

if (typeof valid_binary === 'object') { /* error */ }

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM