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

Preventing default behavior in a JQuery post request

Encountering an issue with jQuery functionality on a mobile device. function send() { $.post("scripts/post.php", { username: $("input[name=username]").val(), password: $("input[name=password]").val() }, function(data) { if ($(".data div" ...

Using Typescript to collapse the Bootstrap navbar through programming

I've managed to make Bootstrap's navbar collapse successfully using the data-toggle and data-target attributes on each li element. If you're interested, here is a SO answer that explains a way to achieve this without modifying every single ...

What is the most effective way to enlarge an HTML table in the center?

Currently, I am dynamically generating an HTML table using a repeater. The table consists of four columns that I populate with company data. My goal is to enable users to click on a row and have another row appear below it, containing a Google map and addi ...

JavaScript: Activate the element with the first class of its children

This code is a visual representation of what I'm trying to accomplish... <style> .red{background:red} .blue{background:blue} </style> <div id=test> <button>1</button> <button>2</button> </div> ...

Learn how to create a half and half color scheme in an HTML table

I have created an HTML table that resembles a calendar. Various events are registered in the calendar, each distinguished by its color. However, I am looking to change the colors of the cells to be half and half. https://i.sstatic.net/gaQq2.png The imag ...

A guide on performing record filtering with MongoDB in Java

In Java (using BasicDBObject), I need to exclude certain records from the database that contain a specific string. For example: The field name in my collection is "description". I wish to filter out any records where the value in the "description" field ...

Having trouble getting data to send to node.js server using $.ajax post

Trying to convert a table date into an array and send it to the server side using Ajax post for the first time. Despite following all the suggestions in previous posts, I am still struggling. Utilizing body-parser to extract data on the server side. Any he ...

Automatically close the multiselect dropdown when the user interacts outside of it (varied scenario)

For those interested, check out this jsfiddle link: http://jsfiddle.net/jaredwilli/vUSPu/ This specific code snippet focuses on creating a multi-select dropdown feature. When a user chooses options from the dropdown and then clicks outside of the menu are ...

Attempting to remove certain characters from a given string

let currentDate = new Date(); currentDate.toLocaleString; If I were to console log the value of currentDate, it would show: Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time) However, what if I only want to display the minutes and seconds like 57: ...

Execute a specialized function with imported modules and specified parameters

Within an npm project, I am looking to execute a custom function with arguments, or ideally provide it as a script in the package.json file like this: npm run custom-function "Hello, World". Currently, I have a file called src/myFunction.ts: import * as e ...

What is the best way to assign a percentage width based on a variable in jQuery?

Is there a way to assign a dynamic width value to an element? Here is the code I am using: $(".menu_list_item").css({ width: width + "%" }); Unfortunately, this doesn't appear to be functioning correctly. If anyo ...

Executing a jQuery function automatically & Invoking a jQuery function using the onClick attribute in an HTML element

Having some issues with jQuery and could use some assistance... Currently, I am trying to have a jQuery function automatically execute when the page loads, as well as when a button is clicked. [Previous Issue] Previously, the jQuery function would automa ...

Loading React Components dynamically depending on user input

Looking to dynamically render different Components based on checkbox selections without unnecessary component imports. Using an Array with Component names (using numbers for example) to import each component based on the array values. Considered the foll ...

I seem to be facing some issues with SkipException in testNG. Can anyone provide guidance on what might be

As a newcomer to selenium UI automation, I am currently experimenting with a simple application using Java and TestNG. My goal is to integrate this test with Continuous Integration (CI), but the test environment URL will vary with each deployment. The ke ...

Testing multiple scenarios using junit and TAURUS framework

I am seeking assistance and hoping this post can serve as a valuable resource for others. My current project involves the need to conduct page load testing using the performance tool, TAURUS. Specifically, I am working on a project that includes a login pa ...

What methods can I utilize to increase the speed of my JavaScript animation?

Recently, I implemented a Vue component designed to loop a div over the X axis. While it functions correctly, I can't help but notice that it is consuming an excessive amount of CPU. I am interested in optimizing this animation for better performance. ...

Is there a sophisticated approach to converting a camel-style string to an uppercase enum in Java?

Currently, I am facing the challenge of parsing an enum instance from a string. The issue lies in the fact that my input string is in camel-case style, such as docType, while the enum follows constant-style naming convention like DOC_TYPE. From what I und ...

Why does the text in a div display in Safari 8.2 and Chrome 39, but not in Firefox 34?

In my HTML document, I have a div tag located within the body like so: <div id="content_text"></div>​ Using javascript, I later set the contents of the div like this: var content_text = document.getElementById("content_text") c ...

React encountered an unexpected end of JSON input while streaming JSON data

Currently, I am facing a challenge with streaming a large amount of data from a NodeJS server that retrieves the data from Mongo and forwards it to React. Due to the substantial volume of data involved, my approach has been to stream it directly from the s ...

Using Java Regex to replace all spaces and "[at]" signs in email addresses

I have created a method that utilizes regular expressions to validate email addresses. public String findValidEmail(String searchText) { Pattern pattern = Pattern .compile("([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(&bso ...