Ways to include a line break in the message of a fresh Error instance in JavaScript

I have a function within a service structured like this:

The Policies array contains functions that will throw an error if a policy is violated (e.g. password missing numbers or capital letters).

 function myFunction(policies, password){ 
  var policiesError = ''; 
  policies.forEach(function(policy) {      
    try {
      policy(password, payload);
    } catch (err) {
      policiesError += err.message + '\n';   // Also tried `concat()`
    }
  });
  if (policiesError){
    throw new Error(policiesError);
  }
}

In the controller, I've implemented:

try{
  myService.myFunction(myFunctions, 'password');
} catch (err){
  $scope.policiesError = err.message; // Displayed as {{policiesError}}  
}

The current message output in the controller appears as:

"Password too shortPassword has no lettersInvalid characters in password"

However, the desired formatting should be:

"Password too short
Password has no letters
Invalid characters in password"

It's a seemingly straightforward issue, but despite multiple attempts to tackle it, I'm still struggling.

Any suggestions for achieving a well-formatted message using new Error and proper error handling techniques?

Answer №1

It was @Bergi who pointed out to me that the issue stemmed from a CSS property related to white-space-. While working on a new feature in our code, I overlooked transferring any of the existing CSS and failed to consider this particular aspect. Indeed, CSS was removing the \n characters added through Javascript.

I must apologize for neglecting to investigate something so basic right from the start.

Answer №2

Always remember to use \r\n instead of just \n.

If you encounter an error, make sure to throw it with the following format: 
throw new Error("\r\nDescription of Line 1 error.\r\nDescription of Line 2 error.");

Once thrown, the error will be displayed as:

JavaScript Error line(102): // Your error message is shown below.
Line 1 Description of Error.
Line 2 Description of Error.

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

Using Google Maps API to combine geoJSON properties with fixed text in an infobox

I've been working on a GoogleMaps project where I load geoJSON points and display their "waterlevel" property in an info-box when hovering over a point. However, I want the info-box to show "Water Level = #" instead of just "#". So far, I've man ...

Transform the Data into JSON format

I need assistance converting my data into the correct JSON format. The current structure of my data is as follows: [ "{ id:001, name:akhilesh, }", "{ id:002, name:Ram, }" ] My goal is to transform the above data into valid J ...

Troubleshooting Problem with Express Server Routing

I'm currently facing an issue with my error handling while trying to implement a new route to retrieve a user by their id. Below is the code snippet for this specific route. const express = require('express'); require('./db/mongoose&a ...

What is the procedure for incorporating JavaScript into my tic-tac-toe game's HTML and CSS?

I have created a simple Tic Tac Toe game using HTML and CSS. Although there is no embedded Javascript, I do reference a Javascript file for functionality. Can anyone provide me with the most straightforward Javascript code that will display an 'X&apos ...

How can I make a Vue component close when clicking outside of it?

I am searching for a solution to automatically close a component when there is a click outside of the element. I attempted to use an addEventListener for this purpose. Although it successfully closes the component, it encounters an issue where it fails to ...

Undefined index when decoding JSON data

When calling the save function, a $.post is sent to 'upp.php' as follows: function save(){ var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || []; var newItem = {}; var num = document.getElementById("num").value; newIte ...

jQuery Form Plugin - fails to trigger error callback for Internal Server errors (500)

I am dealing with a situation where my server is returning a Status code 500, but my jQuery Form is triggering the success callback instead of the error callback. My current jQuery version is 1.7.1 and jQuery Form version is 2.73 from March 2011. The serv ...

Tallying responses of "Yes" and "No" in a React form and storing them

I'm currently working on a React form using Material UI components. To keep track of the responses, I have an empty array called questionAns. My goal is to append an element like yes to the array when the Yes radio button is selected in the form. Belo ...

Discover the best practices for integrating @react-native-community/datetimepicker with React Hook Form!

I am attempting to create a date picker that appears when a field with an icon and the current date in string format is clicked. I am using React Native, React Hook Form, and @react-native-community/datetimepicker. Fortunately, I came across an interesti ...

Unable to locate the MoreVert icon in Material UI interface

I am trying to incorporate the MoreVert icon into my application's header to display signout and settings options. I have added the MoreVert icon as shown below, and although the popup appears when clicking on the supposed location of the icon, I am u ...

How to Trigger a Javascript Function from a Wordpress Navigation Menu

On my website developed in HTML, I have the ability to invoke any JavaScript function using an anchor tag like this <a href="javascript:function();"></a> However, when attempting to add this to a WordPress menu option and saving the menu, eve ...

Identifying the specific filter used in Vue-tables-2

Trying to configure a basic server-side vue-tables-2 with dual filters - one dropdown and the other a search field. The challenge here is identifying which filter was applied within the requestFunction() in order to send a server request. My current strate ...

I'm looking for assistance with integrating Splice into a Push operation in AngularJS. Can anyone provide guidance

When pushing an item into $scope.dt, the condition is checked. If day does not equal true, then the pushed item will be spliced or deleted, and the process will continue for the next item. However, if day is true, no splice operation will occur. This logi ...

Share a Node.js Express.js npm package for universal access within the project

Here is my current folder structure. /app.js /src /routes /controllers Within the routes folder, there are multiple javascript files that all require the passport.js package like so: const passport = require('passport'); Is it possible to c ...

Update the image on a webpage within a template using AJAX code

I manage a website that utilizes templates. Within the template, there is a main image that I need to replace on specific pages, not throughout the entire site. I am seeking a way to change this main image to a new one on select pages using Ajax. Upon re ...

The RefreshIndicator from Material-UI fails to display during the first page load

I am facing an issue with displaying a loading icon during the initial page load. The code appears to be correct to me but for some reason, the loading icon is not showing up. I am utilizing the RefreshIndicator component from material-ui for the loading i ...

What is the best way to retrieve the title element from a loaded iframe?

Looking for a way to create a dynamic title for my iframe without manually coding it in. My goal is to extract the src of the iframe, load that object, and then retrieve the title element from it. I attempted using iframe.contentDocument but encountered ...

Update the content on the webpage to display the SQL data generated by selecting options from various dropdown

My database table is structured like this: Name │ Favorite Color │ Age │ Pet ────────┼────────────────┼───────┼─────── Rupert │ Green │ 21 │ ...

Are you experiencing a strange problem with the CSS button when hovering, clicking, or with the border?

Check out the code for this implementation on jsfiddle: https://jsfiddle.net/xuhang1128/cmkbu07s/2/ I utilized React and React-bootstrap to create it. .design2-statusMonitor { margin-top: 20px; .list-group-item { display: inline-block; ...

Node.js suffering from 'empty post method' issue

I am encountering an issue while retrieving values from certain fields in an index HTML. The post method is returning empty values, with { } being returned instead of the expected email, nick, name, and pass values. Here is my server.js code: var mongoos ...