简体   繁体   中英

How to get api reponse error and error message

I'm new to using APIs so some help would be appreciated. I'm posting some data from a form using an API post request. I now need to display a message if this fails, depending on the error and status code. I know I can get the status code like response.status but I also need to get the error itself and/or the error message.

So I'd need something like this

   $.ajax(settings).fail(function (response) {
     if(response.status === 404 && response.error === 'example_error'){
      alert('This failed.')
     }
   });

I also tried to get it something like this respsonse.json() but no luck. The network response in the console looks like this

{"error":"example_error","message":"this is an error"}

My API call looks like this:

const formData = new FormData(thisForm).entries()

    var settings = {
      "url": "{{ section.settings.endpoint }}",
      "method": "POST",
      "timeout": 0,
      "headers": {
        "Content-Type": "application/json"
      },
      "data": JSON.stringify(Object.fromEntries(formData))
    };
    
    $.ajax(settings).done(function (response) {
      alert('success')

      form.reset()
    });

Any ideas how to do this?

Clearly it is not executing the alert block because the "status" property does not exists on the response object. You've got only "error" and "message". Your answer lies in your api's controllers, where you should take care of sending an appropiate http response, and not just a plain object, which it will carry some error message in case of a failure or a success message too.

So, it all depends in which technology you are using in the backend and return an http response from your controllers, each technology would hand to you some methods to return those responses you need, which will carry a status code and other information.

For further learning you can look up for the anatomy of a http response and the official documentation of your backend tech about sending http responses.

I would suggest you simply console.log() the response and explore it, every object in js is a JSON object.

This looks quite old school, I suggest you use axios instead of ajax, in combination with promises. It's way easier:))


import axios from "axios";
import { config } from "../../configuration/config";

export function sendNotification(message: string): Promise<void> {
  return axios.post(
    `${config.http.servicesUrl}/notify/notifications`,
    {
      message,
    },
    {
      validateStatus: (status) =>
        (status >= 200 && status < 300) || status == 404,
    }
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM