RESTEasy hides real exception - java

My code is throwing an exception (due to a bug). In the log, I see:
org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
at org.jboss.resteasy.core.SynchronousDispatcher.handleApplicationException(SynchronousDispatcher.java:323)
at org.jboss.resteasy.core.SynchronousDispatcher.handleException(SynchronousDispatcher.java:199)
at org.jboss.resteasy.core.SynchronousDispatcher.handleInvokerException(SynchronousDispatcher.java:175)
at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:529)
etc...
The stack of the actual exception is not logged. If I wrap my code in a try..catch and log the caught exception I can verify that my code is at fault. No other library in my system does this, even for deeply-wrapped exceptions, so it must be a problem in RESTEasy, perhaps in UnhandledException?
Is there a way to get around this behavior? I can't think of a good reason why it should be hiding the actual exception.
Jetty
Java
Spring 3.0.3
RESTEasy 2.0.1GA

Do you have an ExceptionMapper? See Chapter 27, Exception Handling, in the RESTEasy documentation.
I used RESTEasy to add REST to an existing system, and the existing system has a weird way of wrapping exceptions within exceptions, so my ExceptionMappers do a lot of unwrapping.
Throwable t = exception;
while (t.getCause() != null) {
t = t.getCause();
}
t.printStackTrace();

I don't use RESTeasy, but it appears to be a dispatch mechanism for RESTful web services.
Assuming this is the case, then it has different design goals from other libraries: they are invoked from your application, but RESTeasy is responsible for invoking your application. It therefore has to protect itself from poorly written code. A "last ditch" exception handler is a common way to do this; you'll see the same thing in Swing.
Whether or not it should log the uncaught exceptions is a different matter. Perhaps there's a configuration option to do this. Or perhaps you need to add a couple lines of code. It is open-source, after all, and I'm sure the maintainers would appreciate a well-written bug report with patch.

Yes, your exception is swallowed by RESTeasy, wrapped in UnhandledException and logged. But your exception lies too deep within to be included in the stacktracs.
To print out your exception to the console, you could append the following to 'WEB-INF/classes/logging.properties'
org.apache.catalina.core.ContainerBase.[Catalina].level = FINEST
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

Related

Exception for REST services for invalid input requests

I am currently developing REST services and throwing BadRequestException for all of the following,
1. Path parameter is invalid
2. Query parameter is invalid
4. Input request object has missing attributes
Is there any specific exceptions for each case like InvalidParameterException or so..? Is there any documentation available to learn which exceptions should be thrown on what situations?
I think it's a personal decision and the answer will depend on your needs to have more detailed expceptions or not.
There are two ways to handle errors with JAX-RS:
Throwing a WebApplicationException
That's the approach you are using, which allows you to map exceptions that extend WebApplicationException to HTTP error responses.
I think throwing a BadRequestException is just fine for all the situations mentioned in your question. Just remember adding a detailed message explaining what was wrong.
If you need a more specific exception, you could consider extending the BadRequestException or maybe the ClientErrorException. The new exceptios could encapsulate the message which explains what the problem with the request. It's up to your needs.
For more details on the exceptions provided by the JAX-RS API, have a look at the javax.ws.rs package documentation. If they do not fit your needs, just extend them and create your specific exceptions.
Using an ExceptionMapper
In other cases it may not be appropriate to throw instances of WebApplicationException, or classes that extend WebApplicationException, and instead it may be preferable to map an existing exception to a response. For such cases it is possible to use a custom exception mapping provider.
Consider, for example, you decide to throw an IllegalArgumentException whenever you received an inapropriate value for your query or path parameters. You can create an ExceptionMapper to map the IllegalArgumentException to a response with the 400 status code:
#Provider
public class IllegalArgumentExceptionMapper
implements ExceptionMapper<IllegalArgumentException> {
#Override
public Response toResponse(IllegalArgumentException exception) {
return Response.status(400).entity(exception.getMessage())
.type("text/plain").build();
}
}
For more details, have a look at the Jersey documentation.
All 3 errors sound like client errors, as the client fails to abide by the contract - so I would return a HTTP 400 Bad Request - perhaps with an explanation in the body of the response.
I believe usually you would create separate cases depending on how you would like to handle these errors. For example, you will have 3 different exceptions to represent your errors.
Most frameworks then allow you to install ExceptionMappers. These map your exceptions to an HTTP response code. These are documented and you should follow them:
For example: http://www.restapitutorial.com/httpstatuscodes.html
In your case for example, I would throw IllegalArgumentExceptions for all those 3 cases and install a mapper, mapping this to a 400 response code with potentially some info.
This can be for example important since the client consuming your service will not receive your exceptions anyway, but rather analyse the response code of the request. With a 400, a user will then know that the request was invalid and won't be retried. You can have similar cases for all sorts.
To read about exception mappers, for example with the help of jersey:
https://jersey.java.net/documentation/latest/representations.html
So to your question:
No, I don't believe there is any best-practise on what Exceptions are thrown from your application. Usually REST frameworks don't have specific exception mappers other than a catch-all mapper that will return a 500 (Internal Server Error)
There is however documentation for REST and the HTTP with regards to which responses should be returned for specific use cases. You should try and design your REST endpoint to conform to those standards for maximum reusability and understandability.
I hope that helps,
Artur

Primefaces 5 <p:ajaxExceptionHandler /> java.lang.Exception handling

When using
<p:ajaxExceptionHandler type="java.lang.Exception" >
or
<p:ajaxExceptionHandler type="java.lang.Throwable" >
the primefaces' exceptions handling mecanismm seems not working !!
My question is how can i use primefaces ajaxExceptionHandler to handle all the inhereted exceptions, no matter what exactely it is (NullPointerException, OutOfBoundException..etc) ?
i just have to mention that the <p:ajaxExceptionHandler> works fine when i use it with
javax.ejb.EJBException, java.lang.NullPointerException or other custom Exceptions.
Remove the type declaration so it's <p:ajaxExceptionHandler />
Also Omnifaces is good but, but obviously requires a new jar dependency, if PF now has the ability you may find it works for you. I however, like that Omnifaces is configured in web.xml and you can set it up to handle/cater for ajax and non ajax request with a page redirect.
This is new to PF5 so any issues let them know.
For more info see for usage
Jsf Ajax Error Handler Usage
Or
PF5 Exception Handler
If not defining a type doesn't work, ensure that in your WEB.XML has defined the error page for java.lang.Exception - if it's not defined there the type definition in your pages won't work.
After reading: PF5UG
I'm still not convinced either however - I will do some checks when i get home,.

Load error messages in singleton bean in spring

I have error_messages table, which contains the site-wide error messages.
I use the error messages across application. So, I created singleton bean of error messages (ErrorMessagesLoad.java)
ErrorMessagesLoad uses ErrorMessageDao to retrieve the error messages from database.
Should I create static variable in ErrorMessagesLoad to hold all the error messages and use it in all classes? or is there better way of doing it?
Thanks,
Satya
You should use your own implementation of MessageSource in Spring to resolve any messages. Here is a good point to start.
When implemented, you just wire your bean to any service or controller and it handles messages for you, with ability to iternationalize them.
In general global static variables should be avoided. Error handling can get tricky. Many applications try to put a global catch handler somewhere near the top (e.g. web applications the top would be filters) which has the ErrorMessagesLoad injected into it. That handler catches underlying exceptions, translates them into something user readable and then throws that higher.
Some examples include Spring's exception translation filter and Jersey's exception mapping mechanism.

how to handle exception thrown while rendering view

For exceptions thrown while handling a request, Spring has a number of different ways to register exception handlers. Is there a way to apply similar exception handling when the exception is thrown while rendering a view? At a minimum I'd like the ability to perform some logging.
The problem is that exceptions thrown during View rendering cannot do an awful lot. In particular, they typically can't render a HTML page containing an error report ... or even send a 5xx response ... because the response will typically have "committed" before the exception is thrown.
So the best you can do (probably) is:
create a wrapper for the View object that catches and logs the exception, or
do the logging in a servlet filter,
But the chances are that the web container can be configured to log uncaught exceptions anyway.
UPDATES
I just noticed spring's HandlerInterceptor class exposes an 'afterCompletion' method which will be invoked when exceptions are thrown. Any thoughts as to the benefits of using this vs. a filter?
Try it and see. :-) But given the following, I doubt that it will work.
Using a filter or interceptor does not work for exceptions thrown while rendering a jsp. It does print to err out:
Dec 16, 2012 12:18:03 PM org.apache.catalina.core.ApplicationDispatcher
invoke SEVERE: Servlet.service() for servlet jsp threw exception
javax.el.PropertyNotFoundException: Property 'fooo' not found on
type java.lang.String"
Unfortunately the exception is not propagated upwards to the filter. I'd like to add my own logging which sends out error notifications and logs additional information about the failed request. Keeping an eye on log files to spot errors isn't a good option.
The chances are that the log message is actually produced using the logging subsystem. If it is, you can use the logging configuration to add your own handler for JSP engine logging events and send out special notifications.
The fact that the exceptions are 1) being thrown during JSP view rendering, and 2) the JSP engine is not propagating them means that (IMO) it is unlikely there is a way for you to catch them.
The other option is to set up a scanner for the log files ... as part of your general system monitoring.

Proper EJB Exception handling - ClassNotFoundException from client

I have some EJBs that use Hibernate to persist data to the database. I have a thick Swing client that talks to these EJBs. The client knows nothing about the database (no driver jar).
During one transaction a Hibernate ConstraintViolationException can be thrown. I catch all exceptions and wrap them in an EJBException like so:
catch(HibernateException e) {
e.printStackTrace();
throw new EJBException(e);
}
The problem I am getting is that when the exception is unmarshalled by the JBoss Invoker on the client side, a ClassNotFoundException is thrown (for PSQLException) since the client has no sql driver jar in the classpath.
I changed this application to always pass the caught exception to the ejbexception constructor like this so we could have a stack trace history. Now I am finding why the original developers didn't do this.
At this point I see two options - either include the postgres driver jar with the client, or remove passing the caught exception to the EJBException constructor. I am curious if anyone has any other suggestions and also how others handle exceptions in their EJBs?
My take is that the client, end user, doesn't need to know the technical details of the problem. Hence at various layer boundaries it's quite reasonble to convert a technical exception to a general "An error of nature XYZ ocurred".
A scheme I've seen used is for the server to allocate a unique error number at the point the exception is detected. It then writes diagnistics to its logs including that number. Messages reported to the client simply include the number. A support desk can then correlate the user's report of the issue via that specific error number.

Categories