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.

Question:angualr 2 typescript client returning 400 response on model valdiation error handlign

See original GitHub issue

I’m using angular 4 with a .net core web api and returning a 400 response in case of model validation. This is the method on the controller

[HttpPut("crea-utente")]
[Authorize(CfgAutorizzazioni.AutSistema.Utenti.UPDATE)]
[ProducesResponseType(typeof(Guid), 200)]
[ProducesResponseType(typeof(DgkErrorResult), 400)]
public async Task<Guid> CreaUtente([FromBody] CreaUtenteDTO dto)
{                        
    return await _mediator.Send(new UtenteCrea.Request(dto, ClienteCodice, CodiceApplicazione, ConnessioneId));
}

this is the client generated from the typescript client generator

    creaUtente(dto: CreaUtenteDTO | null): Observable<string> {
        let url_ = this.baseUrl + "/api/UtenteLocale/crea-utente";
        url_ = url_.replace(/[?&]$/, "");

        const content_ = JSON.stringify(dto);

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

        return this.http.request("put", url_, options_).flatMap((response_ : any) => {
            return this.processCreaUtente(response_);
        }).catch((response_: any) => {
            if (response_ instanceof HttpResponse) {
                try {
                    return this.processCreaUtente(response_);
                } catch (e) {
                    return <Observable<string>><any>Observable.throw(e);
                }
            } else
                return <Observable<string>><any>Observable.throw(response_);
        });
    }

    protected processCreaUtente(response: HttpResponse<Blob>): Observable<string> {
        const status = response.status;

        let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
        if (status === 200) {
            return blobToText(response.body).flatMap(_responseText => {
            let result200: any = null;
            let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
            result200 = resultData200 !== undefined ? resultData200 : <any>null;
            return Observable.of(result200);
            });
        } else if (status === 400) {
            return blobToText(response.body).flatMap(_responseText => {
            let result400: any = null;
            let resultData400 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
            result400 = resultData400 ? DgkErrorResult.fromJS(resultData400) : <any>null;
            return throwException("A server error occurred.", status, _responseText, _headers, result400);
            });
        } else if (status !== 200 && status !== 204) {
            return blobToText(response.body).flatMap(_responseText => {
            return throwException("An unexpected server error occurred.", status, _responseText, _headers);
            });
        }
        return Observable.of<string>(<any>null);
    }

But in case of model validation error the response is not an HttpResponse but rather an HttpErrorResponse so the processCreaUtente is not invoked in the catch.

So something is wrong in my configuration but I can’t figure out what. Any suggesttions will be much appreciated. Thanks. Luca

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:10 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
llusetticommented, Nov 22, 2017

I made some tests and this would get me the actual error, but I’m not an expert so maybe this is completely wrong.

  1. Change the check in the catch from HttpResponse to HttpErrorResponse
  2. Convert the HttpErrorResponse to a HttpResponse<Blob>
if (response_ instanceof HttpErrorResponse) {
  try {
    const httpResponse = new HttpResponse<Blob>({body: response_.error, headers: response_.headers, status: response_.status, statusText: response_.statusText, url: response_.url});
    return this.processTest(httpResponse);
  } catch (e) {
    return <Observable<MyDTO | null>><any>Observable.throw(e);
  }
} else
  return <Observable<MyDTO | null>><any>Observable.throw(response_);

In my case the response_.error of the HttpErrorResult is a blob with the json of my error dto. I hope I was clear enough.

Luca

0reactions
RicoSutercommented, Dec 8, 2017

Thanks for reporting back.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Handle 400 Bad Request From WebApi In Angular 6 (using ...
Below is an Asp.net Core WebAPI which returns bad request with Error details as to its param when let's say duplicate a user...
Read more >
Display Server Side Validation Errors with Angular - | juri.dev
What status code should we use for validation errors? Is it a 500 (server error)? 400 (bad request)? 500 is more like a...
Read more >
HTTP client - Handle request errors
Two types of errors can occur. The server backend might reject the request, returning an HTTP response with a status code such as...
Read more >
Error handling - Apollo GraphQL Docs
If Apollo Server can't parse the request into a legal GraphQL document and validate it against your schema, it responds with a 400...
Read more >
Handling Exceptions Returned from the Web API
A 400 error, BadRequest, is used when you have validation errors from data posted back by the user. You pass a ModelStateDictionary object ......
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