Skip to main content

MVC 3 - Error handling

Cat de mult va place ecranul galben intr-o aplicatie web? Cred ca e la fel de faimos ca si ecranul albastru din Windows. Mai este numit si YSOD – Yellow Screen Of Death. Acest ecran nu ar trebuii sa apara niciodata in productie. Mai jos o sa vorbim despre doua modalitati cum putem sa evitam acest ecran.

MVC 3 ne aduce o functionalitate build-in pentru handling la erori. Atributul HandleErrorAttribute se ocupa de acest lucru pentru noi si face o treaba foarte bine atata timp cat este folosit corespunzator. Putem sa il folosim in doua metode.

O metoda este sa decoram controlerele sau actiniile cu acest atribut. In acest mod, orice eroare care apare in controlerul/actiunea noastra o sa fie prinsa de catre MVC 3. O alta variant este sa adaugam in lista de GlobalFilter si atributul nostru – acest lucru se face in Global.asax.cs - Application_Start. In acest fel nu are importanta de unde vine eroare, o sa fie facut handle la eroare de catre MVC 3.

[HandleError]
public class HelpController : Controller
{
[HandleError]
public ActionResult Index()
{
return View();
}
}
sau
protected void Application_Start()

{
RouteTable.Routes.Add(new HandleErrorAttribute());
}
Dupa ce am facut acest pas trebuie sa active custom errors. Acest lucru se face din fisierul de configurare, in sectiunea system.web:

Configurarea facuta cu atributul de mai sus functioneaza doar pentru erorile de tipul 500, pentru erorile de tip 404, este nevoie sa specificam exact pagina la care facem redirectarea.

In loc sa folosim o pagina HTML, putem sa facem o redirectare spre o actiune a unui controller. View-ul default care se foloseste in cazul in care apare o eroare se gaseste in “/views/shared/Error.cshtml”. By default, acesta afiseaza numele la exceptie, mesajul si locatia de unde a fost aruncata (control + actiune). In cazul in care vreti sa schimbari redirectarea care exista by default, se pate face in felul urmator:

filters.Add(new HandleErrorAttribute
{
ExceptionType = typeof(MyCustomException),
View = "MyCustomError", // Un view care se afla in directorul de shared

// cu numele MyCumstomError.cshtml
Order = 2
});
Trebuie avut grija cum se face handling la errorile de tip 404. O sa scriu putin mai tarziu o explicatie mai detaliata despre 404.

Comments

Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.
publ…