4
I’m willing to use the Global Error Handling with Webapi 2.
I created a new project, within it I created the following class:
Errologteste.Cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Http.ExceptionHandling;
namespace ApiTesteErro
{
public class ErroLogTeste : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
Trace.TraceError(context.ExceptionContext.Exception.ToString());
}
}
}
Then I changed the remote Home
as follows:
Homecontroller.Cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ApiTesteErro.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
int x;
var a = "j";
x = Convert.ToInt16( a);
return View();
}
}
}
I added the service in Webapiconfig:
Webapiconfig.Cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
namespace ApiTesteErro
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new ErroLogTeste());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
I also tried with config.Services.Add(typeof(IExceptionLogger), new ErroLogTeste());
and it didn’t work
When I turn, he misses the x = Convert.ToInt16( a);
, but does nothing in my class ErroLogTeste
.
What else do I need to do for him to run the log?
Add this here after registering the routes. config.Filters.Add(new Exceptionhandlingattribute());
– PauloHDSousa
Ever tried to use
config.Services.Add(typeof(IExceptionLogger), new ErroLogTeste());
instead ofGlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new ErroLogTeste());
– Rodrigo Reis