Learning how to detect errors and utilize the .then() method in a single function with JavaScript

One issue I faced is that when axios encounters an error, .then() (used to display success message) doesn't work. So, I decided to include .catch() to handle errors. But how can I structure the function to both catch errors and implement .then() for successful requests?

I am looking to integrate the following code snippet:

.then(() => 
            {
                swal({
                    title: "Message sent successfully!",
                    type: "success" 
                }).then(function(){
                    location.reload()
                })
            })

Into this existing function:

axios.post('http://localhost:5291/api/Mail', {
        "to": url,
        "subject": document.getElementById("ContactSubject").value,
        "body": `<h3>From:</h3> ${document.getElementById("ContactEmail").value} <br>
                 <h4>Name:</h4> ${document.getElementById("ContactName").value} <br>
                 <h4>Message:</h4> ${document.getElementById("ContactMessage").value}`
    }).catch((error)=> {
        swal("Something went wrong!" , `${error.message}` , "error")
        .then(function(){
            location.reload()
        })
    })

Answer №1

There is a way to handle both success and error cases:

axios.post(...)
  .then(res => alert('Success'))
  .catch(err => alert('Error'))

If you need to perform an action in both the success and error scenarios, you can use the finally clause like this:

axios.post(...)
  .then(res => alert('Success'))
  .catch(err => alert('Error'))
  .finally(() => alert('Processed'))

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

A guide on using AXIOS in React to update data via API end points with query parameters

My API endpoint is “/api/user/self/, which accepts GET and PUT requests When updating user information, a PUT request with the user document in JSON format is required: { "name": "Test", "communications": { "email&q ...

What is the best way to navigate to a specific div while scrolling on a webpage?

Can anyone help me figure out how to make my page scroll between vertical divs directly, instead of the normal scroll behavior? I've tried using the ScrollTo plugin, but it's not working as expected because the example uses buttons for scrolling. ...

Exploring the capabilities of setState within conditional statements in React Native

Hello there! Currently, I am attempting to export exportTest to a separate js file in order to re-render. Here is my approach: import React, { useState } from 'react'; import { StyleSheet, View } from 'react-native'; var n; export var ...

Decode the string containing indices inside square brackets and transform it into a JSON array

I have a collection of strings that contain numbers in brackets like "[4]Motherboard, [25]RAM". Is there a way to convert this string into a JSON array while preserving both the IDs and values? The desired output should look like: {"data":[ {"id":"4","i ...

What steps can I take to stop a website in an iframe from causing the entire page to refresh?

My website includes an iframe that showcases different websites submitted by users. This feature works well, but there is an issue with certain sites causing the whole page to refresh and redirect users away from my site. I want to prevent this initial r ...

Challenges regarding variable scope in JavaScript

Presented below is the JavaScript code I am currently using, which involves jQuery: function language(language) { var text = new Object(); $.ajax({ type: "GET", url: "includes/xml/languages/" + language + ".xml", dataType: ...

Looking for assistance in reorganizing columns in Google Sheets while appending data

Rephrasing a previous post for better understanding- I have a JSON API that I am importing into Google Sheets. However, the columns are not consistently in the same order each time it reloads, which is common for JSON data. The issue arises when I try to ...

Checking the validity of an input element with jQuery: How to determine if the valid or invalid pseudo-class has been applied?

Is there a way to check for the application of the CSS3 :valid or :invalid pseudo-class on an input element using jQuery? I want to verify if the form element has passed CSS validation before allowing the submit button to be enabled. Here are some methods ...

Node does not recognize the $or operator

Currently, I am enrolled in an online course and facing a problem with a query issue. Interestingly, the query functions perfectly fine in the shell, however, when executing the js file, an error arises stating: unknown operator: $or. Here is the crucial c ...

Incorporating AngularJs, attempting to send an email through an HTML contact form using PHP on Google App Engine

Here is the HTML code for a contact form: <div class="col"> <h3>Say hello</h3> <div ng-show="error" class="error"> <p>Something wrong happened!, please try again.</p> </div> ...

Discover the steps to retrieve a fresh array in PHP after utilizing sortable.js

Hi there! I am currently utilizing the sortable javascript feature found on Although the script is working perfectly fine for me, being a non-expert in javascript poses a challenge when it comes to generating the necessary code to retrieve an array in php ...

The lack of a defined theme in the makeStyles for @mui/styles sets it apart from @material-ui/core

Struggling to update my material-ui from version 4.11 to version 5 and running into problems with themes. import { createTheme } from '@mui/material/styles'; import { ThemeProvider, StyledEngineProvider, } from '@mui/material/styles&apo ...

Why won't the dynamic button trigger the JavaScript function?

I've been adding a button dynamically to my page using the following code snippet. if (adminInd =='X'){ var adminDiv = $( '<label id=Delegatelbl>Miscellaneous label prototyping.:</label>'+ '& ...

Tips on creating a literal type that is determined by a specific value within an object

In the flow, I am able to create a dynamic literal type in this manner: const myVar = 'foo' type X = { [typeof myVar]: string } const myX: X = { foo: 1 } // will throw, because number const myX: X = { foo: 'bar' } // will not throw ...

Angular 2 Encounter Error When Trying to Access Undefined Property in a Function

Element: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table.component.html', styleUrls: [&a ...

What is the best way to access the element before and after a specific element in an array using JavaScript?

I need to create a function that accepts a string input, searches for its match in an array, and then returns the previous and next elements in the array. const array = [ "11111", "22222", "343245", "5455", "34999", "34 ...

Which is the better option: using a nonce for each function or one for all AJAX calls?

My approach to security in WordPress includes the use of nonces, which serve as an additional layer of protection. These nonces are essentially hashes that are sent to the server and change every few hours. If this hash is missing, the request will be dee ...

All nodes within the Angular ivh-treeview will automatically expand upon loading

Looking to optimize my AngularJS ivh-treeview. I am aiming to have all child nodes expanded without the need for manual expansion. Presently, the tree structure looks like this: $rootScope.nodes= [{ label: 'node1', value: &apo ...

Enable Parse5's case sensitivity

Recently, I've attempted to parse Angular Templates into AST using the powerful parse5 library. It seemed like the perfect solution, until I encountered an issue - while parsing HTML, it appears that the library transforms everything to lowercase. Fo ...

If the value of the "Global Region" field in the PDF form is not empty, then execute the following JavaScript code:

I need to restrict access to a PDF form when the "Global Region" field is filled out. Testing this code can be time-consuming, so I want to confirm that the syntax to check for a NOT NULL value in the Global Region Field is correct. if(this.getField("Gl ...