Best practice for interpreting MVC errors in Angular 2

Viewed 1104

I have a MVC 5 backend written in C#. It serves MVC views written in Razor and also some Angular 2 pages.

What is the best way to handle potential errors when calling server from client? I really would like to establish a pattern that is robust and works in all situations. Below is what I have tried so far.

Backend C# code:

public class MyController : Controller
{
    [HttpGet]
    public ActionResult GetUsers()
    {
        try
        {
            // Lot of fancy server code ...

            throw new Exception("Dummy error");

            return GetCompressedResult(json);

        }
        catch (Exception ex)
        {
            throw new HttpException(501, ex.Message);
        }
    }

    private FileContentResult GetCompressedResult(string json)
    {
        // Transform to byte array
        var bytes = Encoding.UTF8.GetBytes(json);

        // Compress array
        var compressedBytes = bytes.Compress();
        HttpContext.Response.AppendHeader("Content-encoding", "gzip");
        return new FileContentResult(compressedBytes, "application/json");
    }
}

Client side Angular 2 code:

public loadDataFromServer() {
    let response = this.http.get(this.urlGetData)
        .map((res: Response) => res.json())
        .catch(this.handleError);

    response.subscribe(response => {
        // Process valid result ...
    },
        err => { console.error(err); }
    );
};

private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = JSON.parse(JSON.stringify(error || null))
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
}

This is a printscreen of the error object processed by handleError method:

Error object

This all raises some questions:

  1. Is it correct to throw custom HttpException from server?
  2. Is handleError method correct or maybe too complex?
  3. On client side I would like to see the custom error message, but currently it is just found in an enormous "blob" of HTML that is nasty to parse.
  4. Is client side error handling necessary BOTH in get call and subscribe action?
1 Answers
Related