Search code examples
c#angularpostapi-design

Angular catchError firing unexpectedly when received StatusCode object from c#


I have an API call that is working on the C# backend, but the Angular front-end seems to take the C# reply as an error. Note the text of the object is 'comment added' indicating that a 200 OK response was sent back. Why is the catchError function triggering?

C# method:

[HttpPost("AddComments")]
public ActionResult<string> AddComment(BillingComments b)
{
    try
    {
        return StatusCode(200, "comment added");
    }
    catch (Exception e)
    {
        return StatusCode(500, "error adding comment");
    }
}

Angular method:

submitComment(newComment: BillingComments): any {
    return this.http.post('/api/BillingLg/AddComments', newComment)
        .pipe(catchError(this.appSvc.handleError<string>('submitComment', 'comment submitting err')));
}

Error returned by appSvc.handleError:

Service error: submitComment failed Msg: Http failure during parsing for http://localhost:49975/api/BillingLg/AddCommentsStatus: 200Detail: {"error":{},"text":"comment added"}Text: OK & return type specified (failed gracefully)


Solution

  • Angular by default parse the responses from APIs to Object, so by default, it expects JSON string to be returned from the API.

    So you have two options, either to return a JSON instead of the string (Which is recommended), something like

    return StatusCode(200, "{\"status\": \"comment added\"}");
    

    Or you can make the HttpClient expects a string to be returned:

    this.http.post('/api/BillingLg/AddComments', newComment, {responseType: 'text'})
        .pipe(catchError(this.appSvc.handleError<string>('submitComment', 'comment submitting err')));