Overriding Grails uncaughtExceptionHandler - grails

I am using Grails 2.3 to create a REST API, and I want a better way to handle rendering error responses as a JSON response. What is have currently is a package of exceptions that all have a toJSON method. So all my controller methods wrap everything in the same try/catch blocks and render any error responses the same way.
What I really want is to have an uncaught exception handler that does all this without having to wrap everything in try/catch. So if there's an uncaught exception, it'll automatically convert the exception into JSON, set the appropriate status code, and write and flush the response.
Given all that, here's the actual question:
So the first question is: is this a dumb idea?
Since Grails handles all the thread pooling, I think I would need to register my handler at the beginning of every api call. Should I do this in the beforeInterceptor closure of each controller?
Also, how would I be able to access the response object from my handler in order to be able to write the proper response?
Even if someone could point me to the relevant grails classes in the docs, that would be a big help. I searched and could not find the classes where grails does this to see if I can use their existing classes instead of writing my own.

http://grails.org/doc/latest/guide/theWebLayer.html#mappingToResponseCodes might help. In essence, mapped custom ErrorController could render uncaught exceptions to JSON,
class MyJSONErrorController {
def handleError() {
def exception = request.exception
// perform desired processing to handle the exception
render exception as JSON
}
}
Doing beforeInterceptor or try catch block in each controller seems overwhelming. As Spring framework advocated, only catch exceptions that you need handle specifically than common errors.

Related

Why can't we directly catch exceptions generated by Kotlin code in oc or swift?

Why can't we directly catch exceptions generated by Kotlin code in oc or swift? Is it because of what processing has Kotlin done?
Exception handling in Swift and Objc is different than what you're used to on the JVM and in Kotlin. That's just something you need to get used to. On the JVM, you can just "catch everything" at a higher level, but in Swift and Objc, you need to tell the caller that you may be throwing an exception, and the caller must call with a try/catch.
Kotlin got rid of checked exceptions. Swift/Objc are on the other end of the spectrum in that there are only explicit exceptions, and you must call them with a try block.
You can add the #Throws annotation to a method that you're calling directly from Swift/Objc, and that will throw exceptions in the way Swift/Objc expect. However, if you don't annotate that methods with #Throws, the app will abort instead.

How to catch exceptions in grails REST controllers

If you use a controller to implement rest APIs, you want to deal with any exception thrown and return a generic or specific well formed REST response.
We can't use global error URL mapping method, as the application has a number of APIs and interfaces with different response requirements, and we also don't know which type of Grails' HTTP error codes will be thrown (e.g don't know if it will be a 400, 422, 500 etc). Also, if we used the error page mappings, we won't be able to put relevant data into the JSON response.
E.g. this will generate a GrailsRuntimeException:
class SomeController {
def payload = request.JSON
def someMethod() {
BigDecimal x = new BigDecimal(payload.notExists)
}
The problem is, it seems impossible to catch any error thrown.
E.g. neither this approach:
def handleRuntimeException(RuntimeException e) {
render("some JSON error message")
}
Nor this approach:
try {
:
}
catch (GrailsRuntimeException e) {
render("some JSON error message")
}
Works - it never catches the error.
Tried GroovyRuntimeException, Exception, MissingMethodException, Throwable etc.
The only solution we can think of is to not do any work in the controller, do everything in a service, where apparently we can catch errors.
This approach:
static mappings = {
"500"(controller: "error")
}
Is not want we need for several reasons:
We have several different APIs in different controllers which would require different response formats.
we also have UI controllers, which would want the default error system which shows the stack trace etc.
We want to handle the error in the controller where the exception happened, so we can clean up, or at least can log or return the stat which only the controller knows.
Have decided the only way is to move all code into services, and do nothing in the controller except pass the request, and render the resultant string. i.e. all parameter handling, especially number conversion, is done in the service.
It's ironic that the solution that you see as suboptimal that you're settling for is exactly what you should always do. This isn't PHP - don't put logic in Controllers (or GSPs).
Services are by default transactional, so they're a great place to put code that writes to the database since that should always happen in a transaction. They're also excellent for business logic whether it's transactional or not, and you can either annotate individual methods with #Transactional to partition the methods into ones that run in a transaction and ones that don't, or split the services into some that are fully transactional and some that aren't.
If you keep all of the HTTP-related code in the controllers, doing the data binding from params, and calling helper classes (services, domain classes, taglibs, etc.) you get a good separation of concerns, and if the service layer doesn't know anything about params, HttpServletRequest, HTTP sessions, etc. then it's easily reusable in other Grails apps and even in non-Grails apps. They'll also be easier to test, since there isn't so much inter-related code that needs to be mocked and otherwise made test-friendly.
Using this approach, the controllers basically become dumb routers, accepting requests, calling helpers to do the real work, and delegating page rendering or response writing, or redirecting or forwarding.
I am very late to answer this, but I think it might help people stumbling and searching for solution.
Here is one of my blogs explaining Custom exception handling in grails and error responses for RESTfull services
Hope this might help someone
I am using grails 3.2.4 and there is no issue as you have explained here. I have moved all business logics inside the service class and catching exceptions by parent controller trait. Here I am handling this exception in another ParentExceptionController trait which is implemented by classes where such exception is occurring from service class. Example:
UserService {
boolean create(Map params) {
throw new InvalidParameterException('some message')
}
UserController implements ParentExceptionController {
UserService userService
userService.create(params.userDetails)
}
trait ParentExceptionController {
Object handleInvalidParameterException(InvalidParameterExceoption exception) {
log.error 'log message'
respond([message: exception.message])
}
first and second both are working in my case.

Where to place exception loggging in ASP.NET MVC

Can anyone please explain difference between below two approaches.
Logging in controller's OnException event:
try
{
//code
}
catch
{
//rollback trasanctions
throw;
}
Or, logging in catch block:
try
{
//code
}
catch
{
//logging here
//rollback trasactions
throw;
}
The Controller's OnException method is used when an unhandled exception occurs in the processing of the request. It is indicates what functionality should happen if an unexpected exception occurs. You should really only use this as a safeguard in the event that you messed up or the system failed in an unexpected, fatal way.
If you are executing some piece of code that you expect to throw a specific exception, wrap it in try block, and handle the specific exception accordingly. This defensive approach will help you debug issues as soon as they happen, rather than wait for them to bubble up to a point where you don't know the cause.
Think about it, if you have multiple action methods and only one OnException method per controller, then you have a much more complex issue to handle, because any of the action methods or filters could have thrown the error. However, if you catch an exception called by a specific service call then you already know exactly what caused the unexpected behavior, and it will be much easier to address accordingly.
Read this for greater understanding: Eric Lippert has an excellent article in which he breaks down the different categories of exceptions that we encounter and offers best practices for addressing them. It is available at http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx . In case you don't know who Eric Lippert is, he is very smart and you should listen to him if you code in C#. His main points are:
Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.
Fix your code so that it never triggers a boneheaded exception – an "index out of range" exception should never happen in production code.
Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid calling a vexing method, catch its vexing exceptions.
Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.
Update
Just realized I didn't explicitly address the "logging" question. It probably makes most sense to avoid handling your fatal/exogenous errors in a controller scope, because you will end up duplicating your logic, often. This behavior is better handled in a global action filter.
This codeproject article Exception Handling in ASP.NET MVC explains how to override the default HandleErrorAttribute and leverage an ErrorController so that it can be applied globally.
In addition, the following 5-part blog series gives an in depth analysis of the different options you have for error handling in MVC applications: http://perspectivespace.com/error-handling-in-aspnet-mvc-3-index-of-posts

ASP.Net MVC Try Catch Best Practice

Could anyone please guide me on what's the best practice to handle exception in ASP.NET MVC?
Controller?
Model?
Model (Contains EF logics i.e. save, update etc) throw any exception and catch in Controller?
In any method or block of code where you may expect specific exceptions (interacting with a database or an external service which may or may not not be available, etc.) wrap that code in a Try/Catch to catch the specific exception(s) in question. You'd want to know exactly what kind of exceptions occurred to handle them properly. (Naturally, use a Finally block to dispose of any open resources.) How to properly handle them is up to you and how you want your application to behave.
You should definitely have a global exception handling to catch anything unexpected which falls through the cracks. At no point should an unhandled exception bubble up to the user. The global exception handler should just present the user with a friendly error message and should log the exception and notify you of what happened. Generally, a good goal is to identify the exception and add error handling code to catch it in its localized state before it bubbles up to global. The goal, over time, should be to have as few global exceptions as possible and to have any potentially-exception-generating code have its own error handling to guard against those cases.
An example of the latter could be something as simple as a particular method receiving null arguments that you want to check for before using those arguments. One thing you want to avoid, however, is using exception handling for logic flow. For example...
Let's say you have a method which takes a custom object as an argument:
public MyMethod(MyObject obj)
{
// ...
}
Your original code assumes that obj will always have a value. However, after some time of production use, you discover that obj is sometimes null and that it's throwing a NullReferenceException from within that method, which is being caught by the global exception handler.
You may be tempted to just wrap the code in MyMethod in its own Try/Catch block to catch that exception. This isn't necessarily a good idea (though there may be cases where it is). Instead, you'd want to check for null at the start of the method:
public MyMethod(MyObject obj)
{
if (obj == null) throw new ArgumentNullException("obj can not be NULL");
// ...
}
This encapsulates the method better and allows it to throw controlled exceptions. Exceptions aren't bad things, only unexpected exceptions. Note that the above will still throw the exception which will still bubble up to the global handler. Thus, it's also a good idea to wrap the calls to this method in a Try/Catch block in order to catch the ArgumentNullException and handle it accordingly. Perhaps the code which calls this method can fix the null reference and try again, perhaps it can try something else, etc. You still don't want it to bubble up to the global handler if possible, since this has become an "expected" exception and can be handled accordingly.
Naturally, you still want to avoid the throwing/catching of the expected exceptions in the above example, so similar checks for null should happen before calling the method so that the method isn't even called.
Maybe if the object is null you can directly present the user with an error message and log the error and notify you of as much information about the state of things as possible so that you can research why it's null and fix it. Maybe being null is a perfectly acceptable state of that object at that time according to the logic of the application. If so, check if it's null and don't bother calling the method. Just carry on as normal.
It's a lot of error-checking and handling code, but that's a good thing.
Edit: Another thing to note about exception handling is that you should catch the exception only if you can actually handle it at that time. If the method can't handle it internally, let the exception bubble up from the method to the calling method, and so on. Thus, the only exceptions which should reach the global handler are exceptions which you can't actually handle anywhere in the code (which is why it's a good goal to fix and prevent global exceptions).
"Handle" in this case would mean being able to actually do something about it. Maybe that something is to just log it and carry on, maybe that something is to perform some specific logic, etc. But to catch, log, and re-throw is bad design. If you can't recover from the exception, let it bubble up.
The best way is to catch the exception globally, log it using Elmah. Otherwise you will have to put all your exceptions in your every controller code and that would be a lot of repetition especially for CRUD operations

Spring Security - Prevent AccessDeniedException from stopping application normal flow

I'm using Spring Secuirty 3 with ACL module. I'm securing the methods with #PreAuthentication annotations using a custom PermissionEvaluator. Its working fine, however every time the PermissionEvaluator returns an ACCESS_DENIED an AccessDeniedException is thrown at some point and this stops the application execution. The desired behaivore will be that when the PermissionEvaluator returns and ACCESS_DENIED, the secured method call is only prevented (skipped) and the rest of the application keeps running normally. Does anyone have an idea on how to achieve this?
If you wrap each call where you want this to happen in a try...catch, you can get this behavior. Basically, since it's an exception, any normal exception handling will apply to it. If your application can handle that exception and continue normally, then do exactly that!
Here's an example of what I mean:
// The 1st method that could be denied but you want to continue execution after
try {
// Call method A that will throw the exception
} catch (/*The exception you expect to be thrown and want to continue after*/){}
// The 2nd method that could be denied but you want to continue execution after
try {
// Call method B that will throw the exception
} catch (/*The exception you expect to be thrown and want to continue after*/){}
etc.
Yes, it does add a lot of overhead to calling those methods, but it is a fairly simple way of allowing execution to continue after an exception is raised.
I would also argue that it is also more correct, since the calling code does know how to deal with those exceptions. This also doesn't require any additional Spring configuration, which means that the code behavior remains closer to the default and does not rely on external configurations to determine it's behavior.

Resources