Grails error handler always receives null pointer - exception

We have a custom error controller that gets called after all of our errors. However, most of our errors that get thrown end up coming into the controller as null pointers, even though the original error was not a null pointer. Any ideas? Code below. Bootstrap and UrlMappings available if needed. Thanks
Error Handler method
def HandleErrors =
{
def exception = request.exception.cause.class
if (exception)
{
Exception ex = request.exception //This exception is always a NPE
...
Block of code throwing the exception. I originally did not have a try catch in here, but wanted to add it so that I was sure the exception being thrown was Not a NPE. Its a file not found exception.
try{
def writer = new FileWriter( new File(fileSaveLocation));
}
catch ( ex)
{
throw(ex)
}
Edit: Adding the exception that is pushed to the exception handler
Exception:org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException
Cause:org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

It's not because you're referencing something that is null inside the error handler, and so are inadvertently throwing another exception, which is again caught?
can you try changing:
def exception = request.exception.cause.class
to
def exception = request?.exception?.cause?.class

Related

What will happen if exception thrown of a particular type don't have a catch block corresponding to that exception in c++

For the code given below. How will the code behave and why?
// code goes here..
try {
if(a==0) throw "a is 0";
}
catch(int a) { ; }
a = 19;
//code goes here.....
Since you are throwing a string (aka const char*) but you are only catching values of type int, the exception will not be caught and will go on unwinding the function stack until it finds a try-block willing to catch your exception or it reaches main and aborts your program.
That is, if your catch block does not catch the thrown exception type it is as if it was not there.

How to know exception occurred within grails transaction?

I have a service method which does some operation inside a transaction.
public User method1() {
// some code...
Vehicle.withTransaction { status ->
// some collection loop
// some other delete
vehicle.delete(failOnError:true)
}
if (checkSomething outside transaction) {
return throw some user defined exception
}
return user
}
If there is a runtime exception we dont have to catch that exception and the transaction will be rolled back automatically. But how to determine that transaction rolled back due to some exception and I want to throw some user friendly error message. delete() call also wont return anything.
If I add try/catch block inside the transaction by catching the Exception (super class) it is not getting into that exception block. But i was expecting it to go into that block and throw user friendly exception.
EDIT 1: Is it a good idea to add try/catch arround withTransaction
Any idea how to solver this?? Thanks in advance.
If I understand you question correctly, you want to know how to catch an exception, determine what the exception is, and return a message to the user. There are a few ways to do this. I will show you how I do it.
Before I get to the code there are a few things I might suggest. First, you don't need to explicitly declare the transaction in a service (I'm using v2.2.5). Services are transactional by default (not a big deal).
Second, the transaction will automatically roll back if any exception occurs while executing the service method.
Third, I would recommend removing failOnError:true from save() (I don't think it works on delete()... I may be wrong?). I find it is easier to run validate() or save() in the service then return the model instance to the controller where the objects errors can be used in a flash message.
The following is a sample of how I like to handle exceptions and saves using a service method and try/catch in the controller:
class FooService {
def saveFoo(Foo fooInstance) {
return fooInstance.save()
}
def anotherSaveFoo(Foo fooInstance) {
if(fooInstance.validate()){
fooInstance.save()
}else{
do something else or
throw new CustomException()
}
return fooInstance
}
}
class FooController {
def save = {
def newFoo = new Foo(params)
try{
returnedFoo = fooService.saveFoo(newFoo)
}catch(CustomException | Exception e){
flash.warning = [message(code: 'foo.validation.error.message',
args: [org.apache.commons.lang.exception.ExceptionUtils.getRootCauseMessage(e)],
default: "The foo changes did not pass validation.<br/>{0}")]
redirect('to where ever you need to go')
return
}
if(returnedFoo.hasErrors()){
def fooErrors = returnedFoo.errors.getAllErrors()
flash.warning = [message(code: 'foo.validation.error.message',
args: [fooErrors],
default: "The foo changes did not pass validation.<br/>${fooErrors}")]
redirect('to where ever you need to go')
return
}else {
flash.success = [message(code: 'foo.saved.successfully.message',
default: "The foo was saved successfully")]
redirect('to where ever you need to go')
}
}
}
Hope this helps, or gets some other input from more experienced Grails developers.
Here are a few other ways I've found to get exception info to pass along to your user:
request.exception.cause
request.exception.cause.message
response.status
A few links to other relevant questions that may help:
Exception handling in Grails controllers
Exception handling in Grails controllers with ExceptionMapper in Grails 2.2.4 best practice
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/exception/ExceptionUtils.html

exception tracking and blocking it in zend framework 2

How to stop exception from showing in zend framework 2 and instead when exception is thrown i want to redirect to 404 page .
Actually when user fires wrong url or some how any query gets executed in a wrong way exception is thrown , so i need to block this exception and instead redirect to any other well designed page . I'm unable to track the the exception point or rather catch the exception or from where exception is generated . I have used this code
You can handle the exceptions in anyway you want after catching it as the following example in which you are catching the exception globally...:
In the onBootstrap method i have attached the following code in Module.php in a function to execute when an event occurs, the following attach a function to be executed when an error (exception) is raised:
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$em = $application->getEventManager();
//handle the dispatch error (exception)
$em->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, array($this,
'handleError'));
//handle the view render error (exception)
$em->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER_ERROR, array($this,
'handleError'));
}
and then defineed in module.php only the function to handle the error
public function handleError(MvcEvent $e)
{
//get the exception
$exception = $e->getParam('exception');
//...handle the exception... maybe log it and redirect to another page,
//or send an email that an exception occurred...
}
I found this code from stackoverflow only , but it is not working , i mean when i'm passing wrong parameters in url , it is showing " A 404 error occurred
Page not found.
The requested controller was unable to dispatch the request.
Controller:
Front\Controller\Front
No Exception available "
Please i need help on this.
you can turn off exceptions in zf2 by chaining 'display_exceptions' => TRUE to 'display_exceptions' => false, [module/Application/config/module.config.php]

Also log every exception at error level

Using Groovy / Grails and log4j is there any way to ensure every exception thrown in the code is logged at error level.
Rather than having to find every catch block and explictly log it?
If not groovy / grails - a java suggestion will suffice.
Thanks
I don't believe there's any way to do this for handled exceptions, but you can do it for unhandled exceptions by adding the following to UrlMappings.groovy
"500"(controller: 'error')
Then create an ErrorController.groovy under grails-app/controllers
class ErrorController {
def index() {
Throwable exception = request?.exception?.cause
log.error 'something bad happened', exception
}
}

Unable to catch Exception when passing null body with Content-Type:application/json

I've written an ExceptionMapper in order to catch all http exception (400,404,500,...) in my application.
#Provider
public class MyExceptionHandler implements ExceptionMapper<Exception> {
#Override
public Response toResponse(Exception ex) {
//Some Code to build Response
}
unfortunately when I send a post request with Content-Type:application/json with empty or wrong format body, this error occurs and I can not catch it in MyExceptionHandler.
Status Code: 400 Bad Request
No content to map due to end-of-input
at [Source: org.apache.catalina.connector.CoyoteInputStream#5774bb5e; line: 1, column: 1]
what did I do wrong?
Thanks a lot.
Environment: JAX-RS, GlassFish 3
Edit:
I think this error is related to AppServer and must be handled there.
When there is a bad request such as wrong format body, the WebApplicationException is thrown. Here is how exception mappers are selected
When a WebApplicationException, or one of its subclasses, with an
empty entity body is thrown, the runtime will check to see if there
is an exception mapper that handles WebApplicationException
exceptions. If there is the exception mapper is used to create the
response sent to the consumer.
When any exception other than a WebApplicationException exception, or
one of its subclasses, is thrown, the runtime will check for an
appropriate exception mapper. An exception mapper is selected if it
handles the specific exception thrown. If there is not an exception
mapper for the specific exception that was thrown, the exception
mapper for the nearest superclass of the exception is selected.
Here is what I would recommend
register an ExceptionMapper<WebApplicationException>
register an ExceptionMapper<Throwable> to catch all other exceptions with a generic response signaling a 500 sever error.