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
{
throw new Exception("Dummy error");
return GetCompressedResult(json);
}
catch (Exception ex)
{
throw new HttpException(501, ex.Message);
}
}
private FileContentResult GetCompressedResult(string json)
{
var bytes = Encoding.UTF8.GetBytes(json);
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 => {
},
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:

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, .
- ?