I want to use Global Error Handling with WebAPI 2.
I created a new project, inside it I created the following class:
ErrorLogTest.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 control 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 did not work
When I squeeze it out of error in x = Convert.ToInt16( a);
, but it does not execute anything in my ErroLogTeste
class.
What else do I need to do to run the log?