Tips for creating a unique exception in AngularJS?

I have a customException.js script with the following service:

app.service('CustomException', function() {
this.CustomException1 = function (message) {
    if (!message) {
        message = "Custom Exception 1 occurred!";
    }
    return {
        name: 'CustomException1',
        message: message
    };
  }
});

Now I implement this in another service:

app.service('Operations', ['CustomException', function(CustomException) {
this.operation1 = function(param1, param2) {
    if (!param1) {
        throw new CustomException.CustomException1("Parameter 1 is not defined!");
    } else if (!param2) {
        throw new CustomException.CustomException1("Parameter 2 is not defined!");
    } else {    
      // code to perform the operation.
    }
    }
}])

However, when I utilize the Operations service in a controller without providing the required parameters, my custom exceptions are not caught. No error messages are displayed on the console. The data simply does not show up on the screen. What could be the issue here, and is there a more efficient way to handle custom exceptions in AngularJS?

Answer №1

Check out this functioning plunker link showcasing the code provided, which worked flawlessly for me!

If you're invoking your Joins service from a controller to handle custom exceptions, here's an example of how you can implement it:

var app = angular.module("app", []);
app.controller('Ctrl', function($scope, $http, Joins) {

    $scope.throwException = function() {
        Joins.LEFTJOIN(false);
    };
});

var app = angular.module("app", []);
app.controller('Ctrl', function($scope, $http, Joins) {

    $scope.throwException = function() {
        Joins.LEFTJOIN(false);
    };
});

app.service('Exception', function() {
    this.ArgumentUndefinedException = function(message) {
        if (!message) {
            message = "One or more of the arguments are undefined!";
        }
        return {
            name: 'ArgumentUndefinedException',
            message: message
        };
    }
});

app.service('Joins', ['Exception', function(Exception) {
    this.LEFTJOIN = function(leftArray, rightArray, joinOnLeft, joinOnRight, columnFromRightArray) {
        if (!leftArray) {
            throw new Exception.ArgumentUndefinedException("Left Array is not defined for LEFTJOIN!");
        } else if (!rightArray) {
            throw new Exception.ArgumentUndefinedException("Right Array is not defined for LEFTJOIN!");
        } else if (!joinOnLeft) {
            throw new Exception.ArgumentUndefinedException("Join On Left is not defined for LEFTJOIN!");
        } else {
            // code to do the left join.
        }
    }
}]);
<html>

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1f2128342d20332b32131c062c3610">[email protected]</a>" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
  
  </head>

 <body ng-app="app" ng-controller="Ctrl">

<button ng-click="throwException()">Exception</button>
</body>

</html>

UPDATE

Take a look at the revamped plunker link with the refactored code, including explanations on how to trigger different errors using truth conditions in the Joins service.

 $scope.throwException = function() {
        Joins.LEFTJOIN(true, false, false); //throw no left array
       /* Joins.LEFTJOIN(false, true, false); //throw no right array
        Joins.LEFTJOIN(false, false, true); //throw no join on left array
        Joins.LEFTJOIN(); //throw default exception
        */
    };

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

Send a parameter to be used as a link attribute in a pop-up box

I am seeking a way to pass a URL for my modal that relies on extracting the adder variable from the main HTML document. While I understand how to pass variables as text (using spans) to a modal, I am unsure how to incorporate a variable in an anchor <a ...

Refreshing the display in an AngularJS directive

I've developed a custom directive for handling file uploads in my AngularJS application. The directive is used in multiple places, including on the same page more than once. Each instance of the directive is supposed to display the uploaded file name ...

Loading Ajax content on a webpage

Recently, I've been impressed with the layout of Google Play Store on a web browser. I am eager to replicate that same smooth browsing experience on my own website. Specifically, I want to create a feature where selecting a category or item doesn&ap ...

Is it possible to map through material-ui components within an array in React.js?

I've been attempting to implement material-ui and iterate over it within an array (to create ratings for items, similar to e-commerce websites). Unfortunately, the code is not functioning as expected. When I run it on my localhost server, no stars are ...

Retrieve the numerical key within an md-directive

How can I access a Json object with a numerical key in an ng directive? Take a look at the object below: { 0 : { value : { firstname : "John" , lastname : "Doe" } } I want to retrieve the first name of this object using a md directive like: <th md-c ...

Tips for saving an array of objects in local storage and transferring it from one file to another

Recently delving into the world of localstorage, I've encountered an issue while attempting to store JSON data in one file and retrieve it in another. The JSON data below was fetched from a URL, and my goal is to obtain all the feed objects in the oth ...

Implementing AngularJS to display different divs according to the selected value

I am attempting to utilize the value of an HTML select element to toggle the visibility of specific div tags using AngularJS. Below is the code snippet I have been working with: <body ng-app="kiosk" id="ng-app" > <div class="page" ng-controll ...

unique scope within a personalized directive

Hi, I'm trying to understand isolated scope in custom directives Here is an example of my directive: restrict: 'E', scope: {}, template: '<input type="file" ng-model="myFile" />{{myFile.name}}', link ...

Using AngularJS filters to search through various fields of data

My goal is to conduct a search using multiple fields of a repeating pattern in combination. I am facing an issue where searching by query.$ model does not allow me to search from multiple fields. Specifically, I want to search for the number 1234 along wi ...

Attempting to generate a dynamic menu on a new webpage by pulling data from the WordPress database of a separate site

My goal is to showcase a menu on my webpage using the values extracted from the WordPress database of another website. Here's the progress I've made so far: app.js angular.module('plunker', []).controller('MainCtrl', func ...

Whenever I try to send an email in Node.js, I encounter 404 errors. Additionally,

I have an Angular application with a form that makes AJAX requests. Emailing works fine, but no matter what I set the response to, I get an error for the path '/send'. I assume Node.js expects the path '/send' to render a template or da ...

Although npm successfully loads Grunt, the grunt command is unfortunately not recognized

Previously, I successfully used grunt on this computer for other projects about 4 months ago. Recently, I tried to use grunt for a new project. Despite loading grunt globally and locally, when I type in $ grunt -v, it says grunt is not recognized. It seems ...

What method can I use to adjust the font style when it overlays an image?

Sorry if this is a bit unclear, but I'm trying to figure out how to change only a section of my font when it overlaps with an image while scrolling. If you visit this example website, you'll see what I'm referring to: For a visual represen ...

Having trouble updating ng-table following $http request

In my single-page application, there is an activate function that includes a promise called getNodes() function activate() { var promises = [getNodes()]; common.activateController(promises, controllerId) .then(function ...

Is there a way to prevent items in Dropbox from being selected?

Here is an example of my HTML element: <select class="form-control" ng-model="current.data.sites" ng-options="item.Id as item.Description for item in current.lookups.siteReg | filterByIdArray: current.data.sites"> <option value="">--Data-- ...

Scrolling with jQuery to create a fixed navigation bar

I'm having an issue with my navbar on my website. I used CSS and jQuery to keep it fixed at the top, but now when I click on a menu item, it doesn't scroll to that section of the page. Can anyone help me troubleshoot this problem? ...

JavaScript Radio Buttons

Below are the different radiobuttons: Apple <input type="radio" id="one" name="apple" data-price="10" value="light"/> Light <input type="radio" id="two" name="apple" data-price="20" value="dark" /> Dark <input type="text" id="appleqty" name ...

Retrieving various sets of JSON objects arrays

I have successfully stored an array of JSON objects in the database using the following code: function send_custom_markers() { var reponse = confirm("Send markers to selected contacts?"); if (reponse === true) { var json_markers = new ...

Update a variety of CSS properties simultaneously

Is it possible to change multiple CSS attributes of an element with just one line of code? Currently, if I want to alter various CSS attributes of an element, I have to write separate lines of code for each attribute. For instance: $("div#start").cli ...

Whoops! The input buffer seems to be containing an image format that is not supported while attempting to utilize Next JS next-opt

I initially used the default Image Optimization component in my Next JS app, only to realize that the site could only be hosted on Vercel and not on other web hosting platforms. This limitation prompted me to explore the next-optimized-images package, whic ...