When doing API request, returned error message is different from what server is sending

So, doing an API call from Client over the Server gives me a different type of results.

Instead of receiving an error: AuthenticationError: binance {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."}

I get this error: Error: Request failed with status code 401

Why is that, how could I send my own error message instead of autogenerated by express ?

// Server.js /some/endpoint
const apikey = 'wrongkey'
const apisec = 'wrongsec'
try {
  const balance = await exchange.client.fetchBalance()
} catch (error) {
  // AuthenticationError: binance {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."}
  return error
// Client.js
try {
  request = await api.get(`/api/v1/exchanges/balance`, { params: { uid } })
  return request.data
} catch (error) {
  // Error: Request failed with status code 401 <-- WHY THIS RESPONSE

>Solution :

You’re getting the HTTP protocol confused with the JSON message within the HTTP response.

The HTTP status code 401 is one of many standardized error codes that a server uses to tell your browser (or an API client) if a request was successful or not. It is returned in the response before the headers.

The "code":-2015 error is the response body. It can contain whatever the server wants to say. It can be JSON, like in your example, or it can be HTML, or CSS, or an image file.

As an example: Open a search engine like DuckDuckGo, and open your browser’s developer tools to the Network tab. This will let you see all of the HTTP requests that your browser is making to the server. Start typing something in the search box, and you’ll notice some activity. The page is sending requests to the server asking for autocomplete suggestions. You can poke around and see that the responses will have a status code of 200 and that the response body contains the autocomplete suggestions:

Screenshot of Developer Tools open on DuckDuckGo

What’s happening in your case is that the HTTP status code is 401, which is an error, and your HTTP client is throwing an exception when that happens.

Depending on your HTTP client, you might be able to get the response body (containing the JSON you’re interested in) from the thrown exception.

Leave a Reply