I'm trying to override OnException in Global.asax to handle error and writing log. I'm not sure which part is wrong, I keep on getting the error "MyApp.MvcApplication.OnException(System.Web.Mvc.ExceptionContext)': no suitable method found to override" whenever I rebuild my solution.
this is the code I have in Application_Start()
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
And this is the code I have in OnException()
protected override void OnException(ExceptionContext context)
{
Exception ex = context.Exception;
if (!string.IsNullOrEmpty(ex.Message) ||
!string.IsNullOrEmpty(ex.Source.ToString()) ||
!string.IsNullOrEmpty(ex.StackTrace))
{
WriteLog(ex.Message.ToString(), ex.StackTrace.ToString(), ex.Source.ToString(), "0");
context.Result = new ViewResult
{
ViewName = String.Format("~/ErrorPage/ErrorPage?message={0}&stack={1}&source={2}", HttpUtility.UrlEncode(ex.Message), HttpUtility.UrlEncode(ex.StackTrace), HttpUtility.UrlEncode(ex.Source))
};
}
context.ExceptionHandled = true;
}
The WriteLog() function is tested working in other application, I don't think there's any problem in it and I even tried:
protected override void OnException(ExceptionContext context) {
Exception ex = context.Exception;
context.Result = new ViewResult
{
ViewName = "~/Shared/Error.cshtml";
};
context.ExceptionHandled = true;
}
But nothing work. The error just remain there.
How could such problem occur and how do I fix it? I read many tutorial about this, I don't think I'm spelling OnException() wrongly.
Please help. Thanks
There isn't any OnException inside Global.asax
You have two ways:
Create your own HandleErrorAttribute and register in FilterConfig.cs
public class HandleExceptionsAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
(...)
}
}
FilterConfig.cs:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionsAttribute());
(...)
}
Or, if you have a BaseController where all controllers are inherited from, override the OnException method.
PS: I would go for the filter one.
There is no method OnException in the global asax, that method belongs to the controllers.to handle errors in the global asax use the method Application_Error(object sender, EventArgs e)
Related
I've added EventBus as a binding library in my Xamarin Android project.
I can compile without errors but when I'm trying to register, I get the following error:
Here is the code for the activity
[Activity(Icon = "#mipmap/ic_launcher"]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Forms.Init(this, savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
CrossCurrentActivity.Current.Init(this, savedInstanceState);
LoadApplication(new App());
EventBus.Default.Register(this);
}
protected override void OnDestroy()
{
base.OnDestroy();
EventBus.Default.Unregister(this);
}
[Subscribe]
public void onEvent(DeviceConnectionEvent my_event)
{
throw new NotImplementedException();
}
protected override void OnActivityResult(int requestCode, Result resultVal, Intent data)
{
if (requestCode == 1)
{
wifiManagerInstance.onNetworkDataReceived();
}
base.OnActivityResult(requestCode, resultVal, data);
}
}
It looks like my method is not being detected when eventbus uses reflection
methods = findState.clazz.getDeclaredMethods();
Other methods of the activity are detected as can be seen in the following picture.
Is there anything I can do?
Thanks in advance.
Since I don't have a binding library for EventBus, I couldn't test it, but
you could check to see if your package is imported correctly when you use [Subscribe] attribute.
Here you should use org.greenrobot.eventbus.Subscribe; rather than com.google.common.eventbus.Subscribe;
I think you could also use MessagingCenter to do what you want.
I'm trying to handle exceptions with AOP approach in my Spring/Swing Application and I couldn't make it work.
Main Class:
public class MainFrame extends JFrame {
private JPanel mainPanel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainFrame() {
initializeMainPanel();
}
private void initializeMainPanel() {
exitLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
throw new Exception("test");
}
});
}
}
Aspect Class:
#Aspect
public class AspectTest{
#AfterThrowing(pointcut = "execution(* com.test.MainFrame.*(..))", throwing = "ex")
public void logError(Exception ex) throws Throwable {
// ex.printStackTrace();
}
}
So, I throw an exception within my Mouse Listener and expect to catch it in my AspectTest class' AfterThrowing method but it does not work.
Can someone please help me to understand what I'm missing here?
#AfterThrowing cannot catch exceptions, only notice them and log them or do something similar. If you want to handle exceptions in an aspect you need to use an #Around advice.
I just updated my project from MvvmCross 3.5.1 stable to 4.2.2. After fixing some other runtime exceptions that popped up after the update, I'm stuck with this one.
I am inflating a layout in an MvxFragment:
_rootView = this.BindingInflate(Resource.Layout.my_layout, null);
This throws a Java.Lang.ClassNotFoundException for Mvx.MvxLinearLayout. With the messages:
Binary XML file line #1: Error inflating class Mvx.MvxLinearLayout
Didn't find class \"Mvx.MvxLinearLayout\" on path: DexPathList[[zip file \"/data/app/com.myapp…
I have already installed the MvvmCross.Binding nuget package.
I the following base activity (which worked fine on 3.5.1):
MvxActionBarActivity
/// <summary>
/// Mvx support for the native ActionBarActivity
/// </summary>
public abstract class MvxActionBarActivity
: MvxActionBarEventSourceActivity
, IMvxAndroidView
{
protected MvxActionBarActivity()
{
BindingContext = new MvxAndroidBindingContext(this, this);
this.AddEventListeners();
}
public object DataContext
{
get { return BindingContext.DataContext; }
set { BindingContext.DataContext = value; }
}
public IMvxViewModel ViewModel
{
get { return DataContext as IMvxViewModel; }
set
{
DataContext = value;
OnViewModelSet();
}
}
public void MvxInternalStartActivityForResult(Intent intent, int requestCode)
{
base.StartActivityForResult(intent, requestCode);
}
public IMvxBindingContext BindingContext { get; set; }
public override void SetContentView(int layoutResId)
{
var view = this.BindingInflate(layoutResId, null);
SetContentView(view);
}
protected virtual void OnViewModelSet()
{
}
MvxActionBarEventSourceActivity
public class MvxActionBarEventSourceActivity : AppCompatActivity
, IMvxEventSourceActivity
{
protected override void OnCreate(Bundle bundle)
{
CreateWillBeCalled.Raise(this, bundle);
base.OnCreate(bundle);
CreateCalled.Raise(this, bundle);
}
protected override void OnDestroy()
{
DestroyCalled.Raise(this);
base.OnDestroy();
}
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
NewIntentCalled.Raise(this, intent);
}
protected override void OnResume()
{
base.OnResume();
ResumeCalled.Raise(this);
}
protected override void OnPause()
{
PauseCalled.Raise(this);
base.OnPause();
}
protected override void OnStart()
{
base.OnStart();
StartCalled.Raise(this);
}
protected override void OnRestart()
{
base.OnRestart();
RestartCalled.Raise(this);
}
protected override void OnStop()
{
StopCalled.Raise(this);
base.OnStop();
}
public override void StartActivityForResult(Intent intent, int requestCode)
{
StartActivityForResultCalled.Raise(this, new MvxStartActivityForResultParameters(intent, requestCode));
base.StartActivityForResult(intent, requestCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
ActivityResultCalled.Raise(this, new MvxActivityResultParameters(requestCode, resultCode, data));
base.OnActivityResult(requestCode, resultCode, data);
}
protected override void OnSaveInstanceState(Bundle outState)
{
SaveInstanceStateCalled.Raise(this, outState);
base.OnSaveInstanceState(outState);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
DisposeCalled.Raise(this);
}
base.Dispose(disposing);
}
public event EventHandler DisposeCalled;
public event EventHandler<MvxValueEventArgs<Bundle>> CreateWillBeCalled;
public event EventHandler<MvxValueEventArgs<Bundle>> CreateCalled;
public event EventHandler DestroyCalled;
public event EventHandler<MvxValueEventArgs<Intent>> NewIntentCalled;
public event EventHandler ResumeCalled;
public event EventHandler PauseCalled;
public event EventHandler StartCalled;
public event EventHandler RestartCalled;
public event EventHandler StopCalled;
public event EventHandler<MvxValueEventArgs<Bundle>> SaveInstanceStateCalled;
public event EventHandler<MvxValueEventArgs<MvxStartActivityForResultParameters>> StartActivityForResultCalled;
public event EventHandler<MvxValueEventArgs<MvxActivityResultParameters>> ActivityResultCalled;
}
Switching my base activity to MvxAppCompatActivity fixed the issue.
I Have a url to a webapi, like this:
http://Dynamicweb8724.nl/webapi/NavToDW/?process="
and in the mvc project I have this files:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultApi",
url: "DefaultApi/{action}/{id}",
defaults: new { controller = "Guestbook", action = "Index", id = UrlParameter.Optional, PageID = 1067 }
);
}
}
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "webapi/NavToDW",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
and the Global.asax file:
public class Global : System.Web.HttpApplication
{
public void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.RazorViewEngine());
ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.WebFormViewEngine());
// Fires when the application is started
Dynamicweb.Frontend.GlobalAsaxHandler.Application_Start(sender, e);
GlobalConfiguration.Configuration.EnsureInitialized();
}
public void Session_Start(object sender, EventArgs e)
{
// Fires when the session is started
Dynamicweb.Frontend.GlobalAsaxHandler.Session_Start(sender, e);
}
public void Application_BeginRequest(object sender, EventArgs e)
{
// Fires at the beginning of each request
//GlobalAsax.Application_BeginRequest(sender, e);
}
public void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Fires upon attempting to authenticate the use
Dynamicweb.Frontend.GlobalAsaxHandler.Application_AuthenticateRequest(sender, e);
}
public void Application_Error(object sender, EventArgs e)
{
// Fires when an error occurs
Dynamicweb.Frontend.GlobalAsaxHandler.Application_Error(sender, e);
}
public void Session_End(object sender, EventArgs e)
{
// Fires when the session ends
Dynamicweb.Frontend.GlobalAsaxHandler.Session_End(sender, e);
}
public void Application_End(object sender, EventArgs e)
{
// Fires when the application ends
Dynamicweb.Frontend.GlobalAsaxHandler.Application_End(sender, e);
}
public void Application_OnPreRequestHandlerExecute(object sender, EventArgs e)
{
Dynamicweb.Frontend.GlobalAsaxHandler.Application_OnPreRequestHandlerExecute(sender, e);
}
}
So I can connect. But I can't go to the specific link, like this:
http://dynamicweb8724.nl/webapi/NavToDW/?process=
the outcome is this:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
bij System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() bij System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) bij System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>
Controller:
public class GuestbookApiControllerController : ApiController
{
// GET: GuestbookApiController
public IEnumerable<GuestbookEntry> Get()
{
return ItemManager.Storage.GetByParentPageId<GuestbookEntry>(1067);
}
}
So what I have to change?
But If I put a breakpoint on this method:
public void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.RazorViewEngine());
ViewEngines.Engines.Add(new Dynamicweb.AspNet.Views.WebFormViewEngine());
// Fires when the application is started
//GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
GlobalAsaxHandler.Application_Start(sender, e);
GlobalConfiguration.Configuration.EnsureInitialized();
}
it doesnt hit.
Your route configuration for the WebApi needs to be fixed. You placed the route template of what you wanted into the name of the route rather than the template itself.
Given the intended Url...
http://Dynamicweb8724.nl/webapi/NavToDW/?process="
There are a few changes you need to make.
First your api controller needs to be able to accept the parameter process and I would also rename the controller to follow convention.
public class GuestbookApiController : ApiController
{
// GET: GuestbookApi
public IEnumerable<GuestbookEntry> Get(int process)
{
return ItemManager.Storage.GetByParentPageId<GuestbookEntry>(process);
}
}
And finally you need to properly map the intended URL to the controller action.
public class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
// Convention-based routing.
//This will map to the intended controller
config.Routes.MapHttpRoute(
name: "GuestBookApiRoute",
routeTemplate: "webapi/NavToDW",
defaults: new { controller = "GuestbookApi" }
);
//This is the default api route
config.Routes.MapHttpRoute(
name: "DefaultWebApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The above shows how to do convention based routing. You can also achieve the same with attribute routing. You can take some time and read up on the topic if you want to do attribute routing
I'm working on an ASP.NET MVC 3.0 application, using Ninject as my dependency injection framework.
So I've inherited my controller from NinjectHttpApplication like so:
public class MvcApplication : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
}
protected void Application_Start()
{
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new NinjectDependencyResolver(Kernel));
}
protected override Ninject.IKernel CreateKernel()
{
return new StandardKernel(new QueriesModule());
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" },
new string[] { typeof(HomeController).Namespace }
);
}
}
But whenever I run the application and try to browse to any of my controllers, I get the error:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Home/Index
What's causing this and how do I fix it?
Turns out this was occurring because the NinjectHttpApplication class from which I'm inheriting is calling the OnApplicationStarted() method at startup. So the solution is to remove the Application_Start() method and move all that code into OnApplicationStarted().