Tips for displaying personalized error messages from your REST API in a JavaScript client

I'm utilizing a Java REST API that has been generated using swagger. If the client is unauthorized, I am sending custom error messages in response.

    public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, String authBase64String) throws NotFoundException {
    // do some magic!
    ErrorRequestObject erb;
    ArrayList <ErrorRequestObject> erbs = new ArrayList<ErrorRequestObject>();

    if (authBase64String == null)
    {   
        erb = new ErrorRequestObject(); erb.setError("Missing Authorization in Header"); erb.setPath("Header:Authorization"); 
        erb.setProposedSolution("Authorization Header should contain user:pwd:nhPath as Base64 string");
        erbs.add(erb);
    }
    if (erbs.size() == 0)
    {
            //success code here
    }
    else
    {
        return Response.status(400).entity(erbs).build();
    }   
}

When calling this API using ajax, the script looks like this:

$.ajax({
            url : URL,
            type : "DELETE",
            dataType : "json",
            contentType : "application/json",
            async : false,
            success : function(result){         
                Response.resolve(result);
                console.log("Response  : " + JSON.stringify(result));
               }
        });

If the call to the API is made without the proper authorization in the header, a 400 status is returned as expected. But how can I access the error object created with Java on the JavaScript client side?

Answer №1

Here is an example:

$.ajax({
        url : endpointURL,
        type : "PUT",
        dataType : "json",
        contentType : "application/json",
        async : true,
        success : function(data){         
            Response.resolve(data);
            console.log("Server Response: " + JSON.stringify(data));
           }, 
        error: function(error) { /* your error handling code here */})
    });

Answer №2

If you encounter an error, you can utilize the error function as shown below:

error: function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
}

In this context,

The jqXHR object refers to the XMLHttpRequest, textStatus represents a string describing the type of error encountered, and errorThrown is an optional exception object if one was thrown. This allows you to handle the statusCode and other parameters like so,

jqXHR.status == 400

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

Capturing screen recordings using Selenium and Java seems to be a challenge as it is not working properly

I have developed a new class for recording videos in Selenium Webdriver Automation. Initially, I have included the Monte Media jar as a dependency in the POM file: <dependency> <groupId>com.github.stephenc.monte</groupId> ...

Utilize the scope for promise .then() functions when calling a service

I've just started using AngularJS and I have a question about handling promises in controllers. In my controller, I'm calling a service that communicates with a webservice and returns a promise. I want to apply the data from the promise's s ...

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

Is there a CSS rule that can alter the appearance of links once they have been clicked on a different webpage?

Just starting out here. Imagine I have 4 distinct links leading to the same webpage - is there a way to modify the properties of the destination page depending on which link was clicked? For instance, clicking on link1 changes the background color of the d ...

Utilizing conditional statements and time to dynamically alter the class of an object

I need to change the class of an object based on the time, with two classes available: recommendedspot and notrecommended. The code I've written so far is not displaying the image correctly. Can someone help me troubleshoot this issue? Here is my cur ...

Utilizing Multiple Canvases Simultaneously

I'm facing an issue where I need to crop multiple images on a single page using the canvas tag in HTML5 along with JavaScript. However, only one image is displaying on the page. How can I resolve this? The code snippet that I have attempted is provid ...

Sending an object over to a different page

Need some assistance with displaying JSON data that is being repeated using ng-repeat. { "title": "image title", "description": "Lorem ipsum dolor sit amet, per ea ferri platonem voluptaria, ea eum ubique ornatus interpretaris. Dolore erroribus reprimique ...

OroCrm is ensuring that Symfony2 profiler seamlessly updates the footer data without triggering a 404 error page within a popup

As a newcomer to OroCrm, I recently installed and configured it on my DEV environment using the app_dev.php entry point. After setting up OroCrm, I immediately noticed the Symfony2 profiler bar appearing at the bottom of the interface. While this was a he ...

Converting JavaScript numbers into years and months format

Given an integer, for example 20, I am trying to calculate how many months and years are represented by that number. For 20, the result would be 1 year and 8 months. How can this be achieved using JavaScript? switch (props.term) { case (props.term ...

Sorting Columns in JQuery Datatables

Encountering an issue with JQuery DataTables (datatables.net) where it takes 2 clicks to sort the columns when there are only 2 rows in the table. The first column sorts on the first click, but subsequent columns require multiple clicks. Despite testing th ...

Unable to fetch data using getJSON method

objecten.js var objectData = [ { image: 'gallery/objecten/bear.jpg', thumb: 'gallery/objecten/bear.jpg', title: 'my first image', description: 'Lorem ipsum caption&apos ...

encountering a problem with iterating through a JSON array

After making an ajax call and retrieving select options in json format, I implemented the code below to display these new options in place of the existing ones: success: function (data){ var $select = $('#dettaglio'); $select.html(' ...

Input information into a JSON container

I've been struggling to find a solution for this issue. Here's the JSON variable I'm working with, which includes the names "rocky" and "jhon": var names = [ "rocky", "jhon" ]; Now, I need to add a new val ...

Activate dual AJAX JSON and cycle through multiple alerts each time an "ul li" element is clicked

In my code, I am utilizing two ajax requests. One retrieves a chat userlist column in JSON format, while the other fetches the message history for each user. The functionality works such that when a $('.member_list ul li') element is clicked, th ...

Include a new feature within an onClick event

I'm looking to implement a single page application using React.js and I want to incorporate a list within a material-ui drawer. The goal is to dynamically add elements to an array every time a button is clicked, but I'm stuck on how to write this ...

What is the best way to differentiate and analyze new AJAX output from previous data using div elements?

Embarking on a project to develop a high/low game using JavaScript, I encountered a perplexing issue where the displayed numbers seemed to be out of sync with the variables stored. This discrepancy left me scratching my head as I struggled to get them to a ...

Converting a floating point number to a 4-byte hex string in JavaScript and reversing the process

I have received a hexadecimal data from the server side that is supposed to be in float format. I am trying to convert these hexadecimals into floats using JavaScript, but so far I have been unable to find a suitable method. Can anyone provide assistance ...

Express is throwing a TypeError because it is unable to access the property 'app', which is undefined

On my nodejs server running the express framework, I have been encountering a random error when making requests. The error occurs unpredictably, usually appearing on the first request and not on subsequent ones. It's challenging for me to identify the ...

The W3C Validator has found a discrepancy in the index.html file, specifically at the app-root location

While attempting to validate my HTML page, I encountered the following error: Error: Element app-root not allowed as child of element body in this context. (Suppressing further errors from this subtree.) From line 4347, column 7; to line 4347, column 16 ...

Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows: https://i.stack.imgur.com/8z0T8.png My goal is to have it look like this: https://i.stack.imgur.com/L8g ...