question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Async/Await errors not working as expected

See original GitHub issue

Hello,

I have a API (POST) which returns 204 status code on success, or a 404 / 500 error code if there is an error.

This API is surrounded by a try / catch await call like below

try { await api.doYourThing(requestBody); } catch(ex) { console.log(‘do something with ex’) }

IF the API returns a 422, then it is not going into the catch as expected.

Looking at the generated API from swagger (in summary its code is)…

        responses: {
          204: {},
          404: {},
          500: {},
          default: {}
        },
        serializer: this.serializer
      });
    } catch (err) {
      return Promise.reject(err);
    }
    return Promise.resolve(operationRes);
  }

How can I make it so that anything thats not a 200 / 204 status code is regarded as an error at the service level?

The SWAGGER has the response defined as below


"responses": {
"204": {
"description": "Success"
},
"404": {
"description": "Not Found"
},
"500": {
"description": "Server Error"
}
}

I don’t really want to override the http client.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
amarzaverycommented, Aug 23, 2019

I am not sure if I was clear enough. To be sure, we are on the same page,

can you please provide a snapshot of the responses section of the operation object from your swagger spec?

Shouldn’t the default response be that for a “error status code” that the promise is rejected? Currently, the promise is resolved and I have no way of getting the error code, let alone the error message

If you define a “default” response status code with a proper schema for the Error then Autorest will honor that and reject a Promise with an Error of that schema/type with some caveat as explained below.

As per the swagger specification, the spec author is supposed to describe at least one positive response code and a default for any errors We do support that. For example

  • if you define positive status codes like 200, 201, 202 and a default then any response code apart from 200, 201, 202 will be treated as an Error and will be deserialized based on the schema specified by the default status code…
  • if you do define other status codes like 404, 400, 500, apart from the positive status codes like 200, 201, etc. then Autorest will not treat them as error codes. In fact, the return type of your method will be the union of the schemas of all the defined status codes.
  • When an error is thrown we do add a property called statusCode to the error object which is the response status code. error.body is the deserialized body if a schema was provided for default.

what if I want to handle a 404 or 500 differently? What if I want to capture that error message?

Above explanation is the default behavior. However, we do understand that users may want to specify negative response codes and would have a case where they want to handle each of them differently… For that we have an extension called "x-ms-error-response": true. Take a look at this sample swagger spec and the corresponding generated code.

NOTE: I think the TypeScript generator as of now, does not honor this extension. It will still treat 500 as an expected status code based on the logic defined in the deserialization policy in the runtime and resolve the promise. This bug should be fixed.

@daviwil @ramya-rao-a This should be a simple fix in the generator and the underlying runtime (ms-rest-js).

  • Generator changes: Autorest modeler should be giving us the information whether x-ms-error-response: true was provided for a given response status code. We need to add a new property (something like "isErrorResponse": true | false) in the response section of the operation spec. For example over here. 500: { bodyMapper: Mappers.PetActionError, isErrorResponse: true },
  • Runtime changes: Then in the deserialization policy in the runtime(ms-rest-js) check for the property isErrorResponse while deserializing an expected status code. If true then pretty much follow the same steps that we are doing for processing default status code and reject the Promise with the deserialized Error instead of deserializing it as an expected response.
  • Test changes: In this generator acceptance test we should assert that the promise is being rejected with right error message…
0reactions
joheredicommented, Oct 9, 2020

I’m closing this issue since it hasn’t had activity in a long time please reactivate if you need more clarification.

x-ms-error-response should be handled now by v6 generator

Read more comments on GitHub >

github_iconTop Results From Across the Web

Error handling with Async/Await in JS | by Ian Segers
Now we have the classic problem, thisThrows returns a rejecting promise, so the regular try...catch is not able to catch the error. As...
Read more >
async await not working as expected [duplicate]
I am creating a reader for parsing an excel file. Below is my async function. let readExcelhelper2 = async function ...
Read more >
Error handling with async/await and promises, n² ways to ...
It only moves the errors you expect, so e.g. an unexpected NullReferenceException will not be moved across boundaries unless you explicitly call reject()...
Read more >
An Async Example
This is an example of an http request, for example to fetch // user data from an API. ... it('tests error with async/await',...
Read more >
javascript - await does not wait for Promise to finish
@SachinHooda await operator can only be used inside an async function, failing this would throw a runtime error as "Can not use keyword...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found