Differences between throwing errors, returning error objects, and using callbacks in Javascript

Currently, I am developing an assembler and simulator for a simplistic assembly language that my computer science students use during their classes. The project is being written in JavaScript with the intention of creating a user-friendly interface in the web browser to help students visualize how each instruction impacts the state of the machine.

One particular challenge I am facing is determining the most effective method for conveying error messages from the assembler when it encounters invalid assembly code. At this stage, the assembler's API is quite basic:

var assembler = ... // Obtain the assembler object
var valid_source = "0 mov r1 r2\n1 halt";
var valid_binary = assembler.assemble(valid_source);  // Returns string of binary data (0's and 1's)

var invalid_source = "foo bar baz!";
var invalid_binary = assembler.assemble(invalid_source); // What should be the response in this case?

I have considered several approaches for addressing this issue:

  1. Create and throw a new JavaScript Error object. However, this seems like excessive handling since users may not necessarily need or want intricate details like a stack trace.
  2. Return a string or object containing specific error information. This way, the assembler's user can decide how to handle any errors that arise.
  3. Modify the assembler's API to utilize a callback function instead:

    assembler.assemble(source, function(binary, error) {
      if (error) {
        // Handle the error
      }
      // Process the binary otherwise
    });

  4. Or perhaps explore a different approach altogether?

Any suggestions, insights, or feedback would be highly valued.

Answer №1

In my opinion, all three options could be effective. However, I have a different perspective:

I would avoid the third option because it may give the impression that it is an asynchronous function when it actually isn't.

My preference would be to choose either option 1 or 2. Option 1 may seem a bit excessive, but I believe it closely resembles how compilers operate. Exiting without a zero code and adding a try/catch block to handle errors would be necessary.

Alternatively, returning an error object appears to be the most suitable choice for me.

I suggest returning an Error object, which can be done as follows:

return new Error('Parsing error');

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

An advantage of using the error object is that it provides access to the stack trace and other useful information. More details can be found here.

Furthermore, to determine if there was an error, you simply need to check the variable type:

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

// Or

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

Wishing you the best of luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Route.post() is in need of a callback function, however, it was provided with an [object String

I've been working on developing my own vocabulary app by following and modifying the MDN node/express tutorial. While the MDN tutorial runs smoothly, I'm encountering issues with my version. Below are the errors I'm facing: Error: Route.p ...

Display images that have been uploaded on the page either as a grid view or a list of

In my Reactjs application, I am uploading multiple images to Azure Blob Storage. On a page, there is a button to open the upload form. Once the upload completes, I want to display all these images on the same page. Since the images have different aspect ...

Having trouble retrieving data from MongoDB and rendering it on an HTML page

Creating a Model Named Field.js in Mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/SuperchainV1', { useNewUrlParser: true }); mongoose.set('useNewUrlParser', true); ...

What is the process for restarting the timer within a timer controlled by the react-countdown component?

Looking for guidance on how to implement a reset() function in ReactJS and JavaScript to reset a timer when the "Reset Clock" button is clicked on my webpage. The goal is to have the timer return to its initial value. Open to suggestions on how to achieve ...

``Why is my setFeatureState function not updating the value in my Mapbox map

I've been attempting to change the stroke of a circle upon clicking it on mapbox. Despite following mapbox's documentation, the values don't seem to update. The console is also clear. t.map.addLayer({ id: id, type: 'circle&apo ...

Module not found in Node.js Express JS

I've read several topics on this issue here at stackoverflow, but I am still unable to get my node application running. When I try to run the command: node app.js local I receive the following error: Error: Cannot find module './config' ...

Combinations of Typescript dependent unions

I'm struggling with calling the given union that wraps a function and its argument. Is there a way to call it without having to cast? type Wrapper = { fn: (a: string) => void arg: string } | { fn: (a: number) => void arg: number } let f ...

Transmit information to the controller using jQuery in a C# MVC environment

Here is my jQuery script code snippet. The script works perfectly and stores the data array/object in a variable called dataBLL. var dataBLL = []; $('#mytable tr').each(function (i) { dataBLL.push({ id: $(this).find('td:eq(0)').text( ...

Mastering Data Transfer in jQuery: A Guide to Migrating Event Information from .on(dragstart) to

I need help with transferring information between an .on(dragstart) event and an .on(drop) event. However, when I run the code below in Chrome, I encounter an error message: 'Uncaught TypeError: Cannot read property 'test' of undefined' ...

A guide on linking an object in strapi V4 to a React app

Recently in strapi v4, there was a change in the response API structure from an array to an object. When analyzing the response using Postman on my local strapi API and converting it into raw format with stringify, I noticed that the API response consists ...

Check for pattern using JavaScript regular expression

Utilizing ng-pattern to validate a regular expression. The pattern must include 3 letters and 2 numbers in a group. For example: G-31SSD or G-EEE43 Currently, the pattern only matches the second example. ng-model="newGroup.groupCode" ng-pattern="/^&bso ...

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...

Combining PHP Variable with URL String

<td><input type="submit" onClick="window.location.href='https://www.'.$myValue.'.test.com'" value="Click!"></td> I am trying to create a button that will redirect to one of eight possible URLs based on a variable. How ...

Obtain the selected dropdown value and transfer it to the controller seamlessly without the need to reload the page

Currently, I am facing an issue with two dropdown lists in a bootstrap modal - CATEGORY and SUBCATEGORY. The values in the SUBCATEGORY list depend on the selection made in the CATEGORY list. My goal is to retrieve the selected value ID and pass it to my co ...

Performing an Ajax post request to a PHP script in order to retrieve a PHP variable using XMLHttpRequest

I am looking to dynamically update my table using JavaScript every few seconds. Currently, I have set up an AJAX post request to my update.php file and trigger it if it is set. Then, I execute a MySQL query to retrieve the data and store the resultset in ...

How can I fix the position of the close button when using the paper component of a modal in material ui to ensure responsiveness on the screen

I recently created a cards page where multiple cards are displayed. Each card opens a modal component when clicked, but unfortunately, the close button is not functioning properly. Here's an image showing the issue with the button's position whe ...

Capturing keydown events exclusively in the topmost layer of the HTML document

Currently, I am developing a web application that includes an underlying HTML file with some JavaScript functionality that I cannot modify. In my code, I create a layer on top of this page using CSS with z-index: 1000;. However, I am facing an issue where ...

What could be causing jQuery animate to malfunction on mobile devices when a viewport is present?

Everything seems to be working fine on my desktop webpage, but when I try it on mobile, there is no scroll... $("HTML, BODY").animate({ scrollTop: 500 }, 1000); This post suggests that mobile devices may not scroll on the body, but on the vi ...

Calculating the hour difference between two time stamps (HH:MM:SS a) using moment.js

I have two time without date var startTime="12:16:59 am"; var endTime="06:12:07 pm"; I need to calculate the total hours between the above times using a library like moment.js. If it's not achievable with moment.js, then please provide a solution u ...

Is it possible to use multiple AJAX requests to automatically fill out form fields?

In my Backbone.js web application, there is a form with multiple dropdowns that need to be populated with data fetched from an API. Since all the application logic resides on the client side due to using Backbone.js, I want to avoid populating these dropd ...