Best practice for interpreting MVC errors in Angular 2

I have an MVC 5 backend written in C #. It serves MVC views written in Razor, as well as some Angular 2 pages.

What is the best way to handle potential errors when calling a server from a client? I really would like to create a sample that is reliable and works in all situations. Below 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 the printed screen of the error object processed by the handleError method:

Error object

All this raises some questions:

  • Is it right to throw a custom HttpException from the server?
  • Is the handleError method correct or can it be too complicated?
  • , "" HTML, .
  • ?
+4
1

- Json .

.

handleResponseError Response . , , (Chrome 57), , . , , err.

, , !

Backend #:

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

            throw new ArgumentException("Dummy error");

            // Normal return of result ...

        }
        catch (Exception ex)
        {
            return Json(new { error = $"{ex.GetType().FullName}: '{ex.Message}'" }, JsonRequestBehavior.AllowGet);
        }
    }
}

Angular 2 :

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

    response.subscribe(result => {
        if (result.error) {
            this.displayJsonError(this.urlGetUsers, result.error);
        }
        else {
            // Process valid result
        }
    });
};



private handleResponseError(value: Response | any) {
    let errorMessage = value.toString();
    let response = value as Response;
    if (response) {
        errorMessage = `${response.status}: ${response.statusText}\n${response.toString()}`;
    }
    if (value.error) {
        errorMessage = value.error;
    }
    if (value.message) {
        errorMessage = value.message;
    }
    return Observable.throw(errorMessage);
}

private displayJsonError(url: string, error: string) {
    console.error(`Call to '${url}' failed with ${error}`);
}
+1

Source: https://habr.com/ru/post/1677159/


All Articles