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.

TypeScript client returns a string instead of the body on error

See original GitHub issue

Having an API which returns a body with errors when the server side validation fails returns just a string instead of the body with the specified error type.

I receive the following message when binding to the error handler: Error Code: 400, Message: Http failure response for https://localhost/api/Delegation: 400 OK

This is the generated code in the client:

createDelegation(model: DelegationModel): Observable<void> {
    let url_ = this.baseUrl + "/api/Delegation";
    url_ = url_.replace(/[?&]$/, "");

    const content_ = JSON.stringify(model);

    let options_ : any = {
        body: content_,
        observe: "response",
        responseType: "blob",
        headers: new HttpHeaders({
            "Content-Type": "application/json",
        })
    };

    return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => {
        return this.processCreateDelegation(response_);
    })).pipe(_observableCatch((response_: any) => {
        if (response_ instanceof HttpResponseBase) {
            try {
                return this.processCreateDelegation(<any>response_);
            } catch (e) {
                return <Observable<void>><any>_observableThrow(e);
            }
        } else
            return <Observable<void>><any>_observableThrow(response_);
    }));
}

protected processCreateDelegation(response: HttpResponseBase): Observable<void> {
    const status = response.status;
    const responseBlob =
        response instanceof HttpResponse ? response.body :
        (<any>response).error instanceof Blob ? (<any>response).error : undefined;

    let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}
    if (status === 400) {
        return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
        let result400: any = null;
        let resultData400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
        result400 = ProblemDetails.fromJS(resultData400);
        return throwException("A server side error occurred.", status, _responseText, _headers, result400);
        }));
    } else if (status === 403) {
        return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
        return throwException("A server side error occurred.", status, _responseText, _headers);
        }));
    } else if (status === 200) {
        return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
        return _observableOf<void>(<any>null);
        }));
    } else if (status !== 200 && status !== 204) {
        return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
        return throwException("An unexpected server error occurred.", status, _responseText, _headers);
        }));
    }
    return _observableOf<void>(<any>null);
}

This is how I bind to the response:

this.delegationClient.createDelegation(model).subscribe(
  () => {
    // result
  },
  error => {
    console.log("error", error);
  }
);

The actual result from the server:

{
   "errors":{
      "UserId":[
         "The field UserId is invalid."
      ]
   },
   "type":"https://tools.ietf.org/html/rfc7231#section-6.5.1",
   "title":"One or more validation errors occurred.",
   "status":400,
   "traceId":"|10d16c7b-492a67427ec0a3ef."
}

The response_ is already the mentioned string instead of type HttpResponseBase with the ProblemDetails in the body. Am I doing something incorrect here or is this a limitation/bug of NSwag?

Issue Analytics

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

github_iconTop GitHub Comments

1reaction
curcascommented, Sep 24, 2020

@RicoSuter I found the problem. It has nothing to do with the library/generated code but with an HttpInterceptor which did this.

0reactions
curcascommented, Sep 15, 2020

I’m using 13.7.0 to generate the spec and the angular (10.x) code.

Read more comments on GitHub >

github_iconTop Results From Across the Web

javascript - Throwing strings instead of Errors
Whenever you think of throwing a primitive string value, throw a new Error("<the string>") instead. You can throw errors with messages, you ...
Read more >
TypeScript errors and how to fix them
A list of common TypeScript errors and how to fix them.
Read more >
Improving TypeScript error handling with exhaustive type ...
Instead of sitting back while the server crashes, a responsible developer thinks defensively and prepares for when a malformed request comes in.
Read more >
Documentation - Narrowing
TypeScript is warning us that we're passing a value with type number | string to the repeat function, which only accepts a number...
Read more >
Type-Safe Error Handling In TypeScript
In this post, I introduce the concept of a Result type, which eliminates the need for throwing exceptions, and reduces risk of runtime ......
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