Grails Generic Exception Handling Mechanism - exception

I am a newbie in grails and trying to find a best way for exception handling in Grails.
I am using Grails 2.4.2 with Spring Secxurity Core.
Following are the scenarios that needs to be considered.
Call to the Grails app could be Web Call/Ajax call/ RestFul call.
Response type expected could be a JSON/TEXT/XML/HTML
Exceptions could occur in any layer of the application(Filters, COntrollers, Service, Domain, TagLib, Database)
Proper HTTP Status code has to be set for the exception. (Could be same for all exceptions)
I want to have a least impact on the coding since grails reduces the boiler plate code a lot, i don't want to end up writing redundant codes in each controller.
Consider the above scenario's what could be the best possible approach on this.
Based on the format type( Content-Negotiation in Grails we could determine the Response Type that is to be provided). I was looking at the traits way of adding exception handling in the controller by implementing the traits for all controllers as defined in the Grails User Documentation. What would happen to the security exceptions that is being thrown by the Spring-Security.
When i make Ajax calls, I believe the error call back on the ajax client is determined by the status code of the HTTP Response code.
What I need is a way to forward any exceptions that occur to a generic error controller which should have access to the root cause, any messages associated with it and construct a HTML/TEXT/JSON/XML response out of it and render it to the client.
Is it possible to achieve this. Any inputs are highly appreciated.
Thanks in advance

Related

Why should I build my own error/exception handling into a Webflux application?

When there is some internal exception in a Webflux application, why do I want/need to write code to handle these exceptions? I understand handling issues and returning appropriate ServerResponse bodies when the service client incorrectly invokes a service, or when a non-error-condition (i.e., query returns empty cursor, etc.) occurs.
But, other than generating debug information into a logfile, is there anything to be gained by rolling-your-own exception handling components? This approach makes "more sense" to me in a monolithic application, where one is trying to avoid a scenario where the app "just dies".
But, for a service implementation, especially if there's some incentive not to expose too much about the internal implementation to a client, why wouldn't Spring's default error/exception handling (and "500 Internal Server Error" response/message) be sufficient.
So, after some time and thought (and little, but still helpful-and-appreciated feedback), I guess it boils down to:
(a) - It provides a localized context to "do things", like logging information about the exception/error condition, or categorizing the severity of the exception within-the-context of a server-client interaction.
(b) - It provides a localized context to hide/expose information from a client, based on the nature of the exception/error condition and whether the server is deployed in a production or test environment.
(c) - Being localized, it makes maintenance/modification a bit easier, as the handling of exceptions/errors is not scattered throughout the code.
(a) and (c) are enough to make me believe it's worth the effort.

How to correctly implement ExceptionFilterAttribute in ASP.NET Core

Are there any docs on how to correctly implement ExceptionFilterAttribute? For instance:
What happens when you set context.Result? Will it serialize that result as the overall response? Does it stop applying any further filters?
What happens when you set context.ExceptionHandled? Does that mean "I'm done processing exceptions, please send the response to the client", or does that mean "I've recovered from the exception, continue processing the request"?
When do you call base.OnException or base.OnExceptionAsync, at the beginning or the end? Do you only call it when your implementation doesn't handle the given exception?
Etc.
There's no official doc on this and it's not the most obvious thing to implement, so does anyone have either a) good docs - maybe a blog post, or b) a correct sample implementation?
Documentation about filters in ASP.NET Core.
Documentation about error handling.
Exception filters handle unhandled exceptions that occur in controller creation, model binding, action filters, or action methods. They won't catch exceptions that occur in Resource filters, Result filters, or MVC Result execution.+
To handle an exception, set the ExceptionContext.ExceptionHandled property to true or write a response. This stops propagation of the exception. Note that an Exception filter can't turn an exception into a "success". Only an Action filter can do that.
Exception filters are good for trapping exceptions that occur within MVC actions, but they're not as flexible as error handling middleware. Prefer middleware for the general case, and use filters only where you need to do error handling differently based on which MVC action was chosen.
Regarding "Does it stop applying any further filters?":
Further pipeline execution is stopped if you have unhandled exception, as current method execution is stopped) and exception go up the stack until it is caught in a higher level catch block.
But keep in mind, that final implementation of ExceptionFilterAttribute logic is still in progress. Some changes are expected in next .NET Core MVC 1.1.2.
I have found the following useful explanation is github issue (Exception Filters returns an empty body):
Have confirmed IActionFilters in MVC 5.2.3 and ASP.NET Core 1.1.0 behave the same. However, IExceptionFilters behave differently w.r.t. setting Result but leaving ExceptionHandled==false. Should remove this special case around setting Result.
1.1.0 behaviour is also a regression compared to ASP.NET Core 1.0.x.
Long story about a consistent behaviour for ASP.NET Core:
Users can short-circuit most IFilterMetadata implementations by setting Result. But, only on the way in e.g. OnActionExecuting() can short-circuit but OnActionExecuted() cannot.
To short-circuit IExceptionFilter implementations (which are only called on the way out), users must set ExceptionHandled==true.
Setting ExceptionHandled==true in all IFilterMetadata implementations also ensures an Exception thrown in an action is not rethrown. An overridden Result is used in that case.
In a small, intentional deviation from MVC 5.2.3, setting Exception==null is handled identically to setting ExceptionHandled==true.

JAX-WS exception handling - best way

I'm a bit confused...
I have a webapp exposing soap webservices.
Now I need my ws's clients to get exception my ws methods are generating (custom exceptions and generic exceptions like Hibernate Exception and so on).
I read a lot but I can't figure out a good solution for... can you please indicate me the best way for this?

What is the best way to test a REST API for backwards compatibility?

My goal is to come up with a set of automated tests that will consume some services of an API and check if the compatibility is not broken (by mistake or on purpose).
My initial idea is to get the JSON results and deserialize against the DTOs used in the serialization. The reason is to avoid the manual generation of a schema that can get really big and difficult to maintain. The problem is that libraries like GSON are very robust and tend not to thrown exceptions when some problem happens in the deserialization (unless we write a custom deserializer, that again will take time and maintainance efforts).
Am I going in the right direction here? or is there another way to ensure API compatibility?
(Ideally, I would like to test not only JSON, but also XML responses from the same API.)

Design question: How can I access an IPC mechanism transparently?

I want to do this (no particular language):
print(foo.objects.bookdb.books[12].title);
or this:
book = foo.objects.bookdb.book.new();
book.title = 'RPC for Dummies';
book.save();
Where foo actually is a service connected to my program via some IPC, and to access its methods and objects, some layer actually sends and receives messages over the network.
Now, I'm not really looking for an IPC mechanism, as there are plenty to choose from. It's likely not to be XML based, but rather s. th. like Google's protocol buffers, dbus or CORBA. What I'm unsure about is how to structure the application so I can access the IPC just like I would any object.
In other words, how can I have OOP that maps transparently over process boundaries?
Not that this is a design question and I'm still working at a pretty high level of the overall architecture. So I'm pretty agnostic yet about which language this is going to be in. C#, Java and Python are all likely to get used, though.
I think the way to do what you are requesting is to have all object communication regarded as message passing. This is how object methods are handled in ruby and smalltalk, among others.
With message passing (rather than method calling) as your object communication mechanism, then operations such as calling a method that didn't exist when you wrote the code becomes sensible as the object can do something sensible with the message anyway (check for a remote procedure, return a value for a field with the same name from a database, etc, or throw a 'method not found' exception, or anything else you could think of).
It's important to note that for languages that don't use this as a default mechanism, you can do message passing anyway (every object has a 'handleMessage' method) but you won't get the syntax niceties, and you won't be able to get IDE help without some extra effort on your part to get the IDE to parse your handleMessage method to check for valid inputs.
Read up on Java's RMI -- the introductory material shows how you can have a local definition of a remote object.
The trick is to have two classes with identical method signatures. The local version of the class is a facade over some network protocol. The remote version receives requests over the network and does the actual work of the object.
You can define a pair of classes so a client can have
foo= NonLocalFoo( "http://host:port" )
foo.this= "that"
foo.save()
And the server receives set_this() and save() method requests from a client connection. The server side is (generally) non-trivial because you have a bunch of discovery and instance management issues.
You shouldn't do it! It is very important for programmers to see and feel the difference between an IPC/RPC and a local method call in the code. If you make it so, that they don't have to think about it, they won't think about it, and that will lead to very poorly performing code.
Think of:
foreach o, o.isGreen in someList {
o.makeBlue;
}
The programmer assumes that the loops takes a few nanoseconds to complete, instead it takes close to a second if someList happens to be remote.