Skip to content

Instantly share code, notes, and snippets.

@yzpaul
Last active February 6, 2020 00:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzpaul/805b27275b5126e97f5eff173fabcf79 to your computer and use it in GitHub Desktop.
Save yzpaul/805b27275b5126e97f5eff173fabcf79 to your computer and use it in GitHub Desktop.
An example of a fault tolerant API call from C# to an Angular front-end in Angular 8
//------------------------------------------------------------------------
//Angular Service (calling C#) and handling responses
//retrieves a list of Card, or an empty object and throws an error message
//in console if the result isnt a list of Card objects
//------------------------------------------------------------------------
//GET REQUEST
getAllCards(): Observable<Card[]> {
return this.http.get<Card[]>('/api/GetAllCards', {})
.pipe(catchError(this.handleError<Card[]>('getAllCards')));
}
/*
//EXAMPLE POST REQUEST
getAllCards(): Observable<Card[]> {
return this.http.post<Card[]>('/api/GetAllCards', {}) //note .get changed to .post
.pipe(catchError(this.handleError<Card[]>('getAllCards',Card[]))); //note the Card[] param passed
}
*/
//handleError method in the Ang Service
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
let res = "Service error: " + `${operation} failed\n`
if (error instanceof HttpErrorResponse)
res += 'Msg: '+error.message + '<br>Status: ' + error.status + '<br>Detail: ' + error.error + '<br>Text: ' + error.statusText + '<br>Object: ' + JSON.stringify(result)
if (result != null) //aka is a POST request, pass obj data too
res+=' Error with http request when passing object with a POST request: '+JSON.stringify(res))
else
res+=' for a GET request';
console.log(res)
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
[Route("api")]
[ApiController] //so we dont have to call model.isValid any more. returns 400 status code if model invalid
public class MyController : Controller{
//------------------------------------------------------------------------
//C# API call. returns a List of objects or an HttpErrorResponse
//------------------------------------------------------------------------
[Route("GetAllCards"),HttpGet] //Change GET to POST if needed
public ActionResult<IEnumerable<Card>> getCards()
{
try
{
return _mc.Cards.ToList(); //code to return a list of objects using EF Core
}catch(Exception e)
{
//note that if you are returning a StatusCode the second param MUST be
//an object to be handled by the Angular catchError correctly. Thus the cast to Json
return StatusCode(500, Json(e.Message));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment