Exception handling in groovy server pages - grails

I have been searching the web for the issue I'm facing for quite some time now. I found people facing it, but couldn't get an appropriate solution to the problem. The issue is what would be the best way to handle any exception occurred in an template.gsp ? I know I can use a try-catch there so that my controller don't get the exception, but I did find people saying its not a good practice, but failed to answer why. So is it a wrong way and if it is then is there any better solution to deal with this problem ?

The correct way is with a 500 error handler: http://grails.org/doc/latest/guide/theWebLayer.html#mappingToResponseCodes
If you have a lot of logic in your views that could produce a error consider refactoring the code into a tag library which can incorporate better error handling

It depends on what behavior you want for your application with the error.
If a generic error page works for the application - then setup an error page in URL mappings and ignore the error in the controller.
Do you need a nice custom error that is specific for that case - (or possibly display an alternate page? ), if so then you'd need to a try catch (or do some fun with URL mapping and creating an error controller). The objections that come up in Exception handling in Grails controllers arise around the amount of code required for the error handling in the controller vs the rest of the application - with the error handling code being ~40% of each controller method. This causes the code to seem bad/bloated (and apparently violate the CodeNarc "CatchException" rule).

Related

Is try-catch block really needed in MVC application, when we have Exception Filters in MVC?

We have try catch block for error handling, But in case of MVC we have exception filters. In such case we can handle errors at filter level. i.e. by using exception filters.
So again writing try-catch block at method level is really needed?
MVC has exception filter in order to display error pages, rather than allowing the exception to bubble up to IIS (i.e. crashing the whole app), where you'd get the simple (and ugly) generic error pages.
However, the idea is that uncaught exceptions should actually be a rarity. For the most part, you don't actually want to return a 500 error page, even if it's a "pretty" error page. Catching the exceptions in your code allows you to do defensive coding. In other words, you can try to handle and recover from those exceptions, such that your site still works, and at the worst, you give specific and guided messages to the user regarding how to avoid the error.
Long and short, yes, still important to use try-catch blocks, and I'd argue even crucial. Unless, you specifically mean to return a 500 error (there are some occasions, particular in APIs, where that might be desirable), you should catch and handle every exception yourself.

Handling grails exceptions in controllers to catch and forward

I'm developing a grails plugin that among other things it handles the json render of all responses for our REST APIs. We are handling some common response status as exceptions, such as bad requests, forbidden, etc.
By throwing specific exceptions I then process them in an error controller and set the proper response status.
The preblem We are having is that since We are monitoring our APIs through NewRelic, all exceptions are reported as 500 errors.
I saw that in grails 2.3 you can define exception handlers on the cotrollers, and it works, but defining it one by one is out of the questions, and adding the handler through metaClass is not working.
Any ideas to solve this?
I am not sure what you mean by "defining it one by one is out of the questions" but if you mean that you don't want to add the exception handler methods in all of your controllers you have at least a couple of options. One is that you could define the exception handler methods in a base controller which all of your other controllers extend. Another option is to write an AST transformation which adds the methods to all of your controllers at compile time.
I hope that helps.

MVC Mini-Profiler throws LockRecursionException when modifying RouteCollection

I am seeing a pretty crazy error crop up when using the MVC MiniProfiler. Intermittently, the site I'm working on enters a state where every request results in this exception being thrown:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.TypeInitializationException: The type initializer for 'MvcMiniProfiler.MiniProfiler' threw an exception.
---> System.Threading.LockRecursionException: Write lock may not be acquired with read lock held.
This pattern is prone to deadlocks. Please ensure that read locks are released before taking a write lock.
If an upgrade is necessary, use an upgrade lock in place of the read lock.
at System.Threading.ReaderWriterLockSlim.TryEnterWriteLockCore(Int32 millisecondsTimeout)
at System.Threading.ReaderWriterLockSlim.TryEnterWriteLock(Int32 millisecondsTimeout)
at System.Web.Routing.RouteCollection.GetWriteLock()
at MvcMiniProfiler.UI.MiniProfilerHandler.RegisterRoutes()
in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\UI\MiniProfilerHandler.cs:line 81
at MvcMiniProfiler.MiniProfiler..cctor()
in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\MiniProfiler.cs:line 241
— End of inner exception stack trace —
at MvcMiniProfiler.MiniProfiler.get_Current()
at TotallyNotOverDrive.Boom.MvcApplication.Application_EndRequest()
The error persists until the app pool is recycled. Looks like somehow a lock is being held which prevents the MiniProfiler from trying to register it's routes. This occurs for requests where I am not starting the MiniProfiler, but during Application_EndRequest I call MiniProfiler.Stop(), which seems to result in a MiniProfiler being created when the Current property is accessed. For a simple solution, I modified EndRequest to use the same logic for stopping the profiler as BeginRequest, so if the request is not using the profiler this error should be avoided completely. I would still like to resolve the actual problem before sending this code to production.
My route table is pretty simple, and is only added to within the Application_Start method. We are not using any other third-party code which might be modifying the route table after startup. The only suspect thing I've done with routing is add a custom Route to the table, but it's a pretty straightforward route, I just needed some more complicated pattern matching than a standard MVC route could accomplish.
I looked through the relevant MiniProfiler code and don't see anything that could be causing a lock to go unreleased, so I'm assuming it's a combination of ASP.NET and MiniProfiler conflicting when accessing the RouteTable. I can't reliably reproduce the problem, so I'm wondering if anyone else has had problems like this with routing. Thanks for any help you can offer.
I think I see what is happening, you need to get the routes registered earlier. You are registering them during EndRequest, at this point there may be other requests in the pipeline which are holding read locks on the route table.
The routes are registered in the static constructor of MiniProfiler. If you access any of the settings in MiniProfiler during Application_Start, this will kick off the static constructor that will register the routes.
For example, try adding something like this, just after registering your routes.
MiniProfiler.Settings.PopupMaxTracesToShow = 10;

Best approach of handling exceptions in Struts2?

Can anybody tell me the best approach of handling exceptions in Struts2? I've configured global exception mappings in struts.xml for specific exceptions. I couldnt find the best approach of handling exceptions.I have two approaches in mind.
1) putting try/catch in each method and throwing exceptions from catch block 2)Without catching any exceptions ie., declaring exceptions in throws clause of method so that Framework automatically handles exceptions and picks suitable mapping from struts.xml and displays the respective error page.
If anybody knows or has tutorial link on this exception handling, pls provide me.
Catching and subsequently rethrowing an exception is almost never a good idea. Typically, you only want to have try/catch blocks if there is actually something you can do with the caught exception, such as handle it and move on correctly, or adding additional information to the exception.
Adding throws to a struts method is perfectly acceptable, in the event that what it throws is not something you can handle in your code and you just need to display an error page. Unless there is some gain to the overhead of the try/catch, it is better just to let it unwind on out on it's own.

How to do Specification Testing with ASP.NET MVC Error view

I'm doing BDD on an MVC3 project with SpecFlow. My current specification scenario says that:
Given a user is working on the system
When an error is raised
Then the user should be redirected to error page
And display a link to go back where he came from
How can I test a spec like this? I usually test the controller directly, however the Error view given by the standard MVC3 template has no controller, and no controller is used, because is redirected by the HandleError global filter.
In exceptional cases I use Watin to test that the behavior conforms to what the specification says, however to do that I need a view that raises an error, something that when everything is working i do not have.
Any ideas on testing scenarios like this?
I have a few thoughts on this scenario:
1.) "Given a user is working on the system" is a pretty vague step. What code would be found in the step definition? Unless you have a user class that has a WorkingOnSystem method, it might be worth taking this line out.
2.) Without having seen the rest of your code, I think the target of this feature should be the HandleError filter itself. By its very definition, you know that when it is invoked an error has occurred. All you need to do is instantiate the filter, call the appropriate method, and test the results.
Think about it this way: What does "When an error is raised" mean in your system? If your HandleError filter is not the place, then you probably don't have a place. In which case, you'll need to be more specific.
I think the awkwardness around this spec is due to ASP.Net MVC. When you're dealing with a framework of abstractions, you're sometimes left to "wrap" your specs around some part of it. We just can't go end-to-end easily when the parts of the application come from so many places.

Resources