JSF 2.0 Custom Exception Handler - exception

I’m struggling fully understanding when/how exceptions are thrown in JSF 2.0. I’ve looked for a solution longer than I care to admit. Ultimately, the goal I want to achieve is “handle” an unhandled exceptions. When an exception is thrown, I want to be able to capture information of interest about the exception, and email that to the appropriate site administrators. I’m forcing an error by throwing a new FacesException() in the constructor of one of my backing beans. I had this working great in JSF 1.1 using MyFaces implementation. I was able to get this working by wrapping the Default Lifecycle and simply overriding the execute() and render() methods. I followed this awesome post by Hanspeter to get that working:
"http://insights2jsf.wordpress.com/2009/07/20/using-a-custom-lifecycle-implementation-to-handle-exceptions-in-jsf-1-2/#comment-103"
I am now undergoing a site upgrade to JSF 2.0 using Mojarra’s. And things work great still as long as the exception is thrown/caught in the execute() method, however; the moment I enter the render(), the HttpServletResponse.isCommitted() equals true, and the phase is PhaseId RENDER_RESPONSE which of course means I can’t perform a redirect or forward. I don’t understand what has changed between JSF 1.1 and 2.0 in regards to when/how the response is committed. As I indicated, I had this working perfectly in the 1.1 framework.
After much searching I found that JSF 2.0 provides a great option for exception handling via a Custom ExceptionHandler. I followed Ed Burns’ blog, Dealing Gracefully with ViewExpiredException in JSF2:
"http://weblogs.java.net/blog/edburns/archive/2009/09/03/dealing-gracefully-viewexpiredexception-jsf2"
As Ed indicates there is always the web.xml way by defining the tag and what type of exception/server error code and to what page one wants sent to for the error. This approach works great as long as I’m catching 404 errors. One interesting thing to note about that however, is if I force a 404 error by typing a non-exsitant URL like /myApp/9er the error handler works great, but as soon as I add “.xhtml” extension (i.e. /myApp/9er.xhtml) then the web.xml definition doesn’t handle it.
One thing I noticed Ed was doing that I hadn’t tried was instead of trying to do a HttpServletRespone.sendRedirect(), he is utilizing the Navigationhandler.handleNavigation() to forward the user to the custom error page. Unfortunately, this method didn’t do anything different than what Faclets does with the error by default. Along with that of course, I was unable to do HttpServletResponse.sendRedirect() due to the same problems as mentioned above; response.isCommitted() equals true.
I know this post is getting long so I will make a quick note about trying to use a PhaseListener for the same purposes. I used the following posts as a guide with this route still being unsuccessful:
"http://ovaraksin.blogspot.com/2010/10/global-handling-of-all-unchecked.html" "http://ovaraksin.blogspot.com/2010/10/jsf-ajax-redirect-after-session-timeout.html"
All and all I have the same issues as already mentioned. When this exception is thrown, the response is already in the committed phase, and I’m unable to redirect/forward the user to a standard error page.
I apologize for such a long post, I’m just trying to give as much information as possible to help eliminate ambiguity. Anyone have any ideas/thoughts to a work around, and I’m curious what might be different between JSF 1.1 and 2.0 that would cause the response to be committed as soon as I enter the render() phase of the Lifecycle.
Thanks a ton for any help with this!!!

So this question is actually not just about a custom exception handler (for which JSF 2 has the powerful ExceptionHandlerFactory mechanism), but more about showing the user a custom error page when the response has already been committed.
One universal way to always be able to redirect the user even if the last bit has already been written to the response is using a HttpServletResponse wrapper that buffers headers and content being written to it.
This does have the adverse effect that the user doesn't see the page being build up gradually.
Maybe you can use this technique to only capture the very early response commit that JSF 2.0 seems to do. As soon as render response starts, you emit the headers you buffered till so far and write out the response content directly.
This way you might still be able to redirect the user to a custom error page if the exception occurs before render response.

I have successfully implemented a filter using response wrapper as described above which avoids the response being commited and allows redirection to a custom page even on an exception in the middle of rendering the page.
The response wrapper sets up its own internal PrintWriter on a StringWriter, which is returned by the getWriter method so that the faces output is buffered. In the happy path, the filter subsequently writes the internal StringWriter contents to the actual response. On an exception, the filter redirects to an error jsp which writes to the (as yet uncommitted) response.
For me, the key to avoiding the response getting committed was to intercept the flushBuffer() method (from ServletResponse, not HttpServletResponse), and avoid calling super.flushBuffer(). I suspect that depending on circumstances and as noted above, it might also be necessary to also override some of the other methods, eg the ones that set headers.

Related

Error handling with react-router

I am struggling a little bit to find a good method for error handling with clientside routing with react-router.
Say I transition from one page to another, and an error occurs when attempting to fetch data (using redial), or something errors while trying to render the components for my page. It doesn't seem like these errors hit the onError function I pass to my Router...
I wasn't able to find much information looking around github issues. Does anyone have a good pattern they like for rendering an error page whenever something unexpected happens on clientside transitions?

How to handle the exceptions thrown from item reader?

I want to catch the exceptions thrown from item reader (e.g. reader not open , incorrect token exceptions etc) and handle it. Currently spring batch is throwing them as fatal exceptons and come out of the step.
Please let me know if there is any way to do it?
I faced the same issue whereby I wanted to catch the
org.springframework.batch.item.file.FlatFileParseException
thrown by the FlatFileItemReader and perform some custom handling & logging. Did some research and almost reached the conclusion that I might have to write a custom reader instead of the default reader I was currently using, until I stumbled upon a gem of a section in the Spring Batch documentation: http://docs.spring.io/spring-batch/reference/html/configureStep.html#interceptingStepExecution
You can write a custom implementation of the ItemReadListener<T> interface and over-ride the onReadError(Exception ex) method and then register this listener class in the corresponding step. As such, this method will then be called when the reader encounters an exception while reading from the file. The exception reference will be passed to the method as well using which you can do as you please like logging etc.
Similarly, writing a #OnReadError annotated method is also an alternative if you don't want to implement the ItemReadListener interface separately.
On a different note, if your whole purpose is to skip such exceptions that might occur while reading, you can try adding following to the chunk configuration in the XML:
<skippable-exception-classes>
<include class="org.springframework.batch.item.file.FlatFileParseException"/>
</skippable-exception-classes>
Ref: http://docs.spring.io/spring-batch/reference/html/configureStep.html#configuringSkip
Problem solved! :)

How ColdFusion exception and 404 errors should be handled?

Today I was designing the error handling statergy for a new website. I have gone through all the docs for ColdFusion Excepiton
handling.
Now I have some doubts.
What the best solution for handling 404 errors?
Using onMissingTemplate() method
Sitewide Missing Template option(CFAdmin)
IIS custom 404 error handler.
What is the best solution for exception handling?
What should I use for error logging onError() method or Site-Wide Error handler? Is there any significant difference between
these two?
Do I need to use try/catch block for each and every query that I write?
Because there are some queries where I am sure the query will only fail when the database will fail. So if the database fails ,there is no meaning process the page further using try/catch. What should I do in these situations?
I know this question looks bit subjective , but I can not find a better place than StackOverflow for this.
For handling 404's, its better to handle it at webserver level.
For Sitewide Missing Template, you can specify the same in CF Admin. Ensure that the Sitewide error handler file location, should be relative to CF webroot and not webserver root. The dependent files may be put at the webserver.
Please refer to http://blogs.coldfusion.com/post.cfm/onmissingtemplate, for IIS custom 404 error handler. This recent blog post has a detailed description of 404 and error handling.
The answer is that you should use all three.
onMissingTemplate() is application-specific (remember that you can have multiple applications on a single CF instance).
Missing Template Handler is CF-instance specific.
IIS custom 404 error handler works for non-CF files (e.g., .htm, .html, etc.). You can still, of course, specify a CF template as the custom error handler.
FYI, the application-specific onMissingTemplate() method takes precedence over the CF Admin Missing Template Handler. The latter fires if there isn't an application-specific onMissingTemplate().
As far as exception handling is concerned, that is going to depend on a number of factors, but again a multi-layered approach is good.

cfthrow is this how you use it? (from Adobe's doc)

I was reading the documentation for cfthrow and came accross this
When to use the cfthrow tag
Use the cfthrow tag when your application can identify and handle
application-specific errors. One typical use for the cfthrow tag is in
implementing custom data validation. The cfthrow tag is also useful
for throwing errors from a custom tag page to the calling page.
For example, on a form action page or custom tag used to set a
password, the application can determine whether the password entered
is a minimum length, or contains both letters and number, and throw an
error with a message that indicates the password rule that was broken.
The cfcatch block handles the error and tells the user how to correct
the problem.
Have I been doing it wrong all this time or is this just a terrible use-case?
I was taught that exceptions shouldn't be used to handle regular application flow but for stuff that is somewhat out of your control. For example, a file being locked when you go to write to it.
A user breaking a password rule doesn't quite sound like something that's out of your control.
That is a poor example not a poor use case. I personally would pass in the parameters to a validation function and return a result that contained a pass or fail and a collection of failure messages to display to the user.
How I use exceptions is as follows.
Within functions. Let's say that you have a function that you are getting some data from the database and you are then constructing a structure from it. If the query returned has no values you have several options:-
You could return an empty structure and let the calling code deduce the problem from the fact the structure is empty. This is not ideal because then the application has to have complicated logic to address the missing data.
You could return a more complex datatype where one property is whether the process went ok and the actual data. Again this is not optimal as you have to then make this access the property on every call when the majority of the time you have data and again your application is dealing with this issue.
Or you could raise a custom exception with cfthrow indicating that there is no record that matches. This then means that you can choose to ignore the prospect of this error happening and let it bubble up to the onError handler or you could surround it in a try catch statement and deal with it there and then. This keeps your API clean and sensible.
Wrapping external errors let's say that you connect to an external API using cfhttp over https. Now this requires installing the certificate in your keystore otherwise it throws an error. If this certificate gets updated then it will start erroring again. In this instance I would wrap the call in a try catch and should this be the error I would wrap that in my own custom exception with a message detailing that we need to update the cert in the keystore so that any developer debugging it knows what to do to fix it without having to work it out. If it is not that particular error then I would cfrethrow it so that it bubbles up and is dealt with by whatever exception handling logic is above the call.
These are just a few examples, but there are more. To summarise I would say that throwing exceptions is a way of communicating up through the tiers of an application when something has occurred that is not the hoped for behaviour while keeping your API/Application logic clean and understandable.
It's really up to your discretion. It's extremely common in many languages to use exceptions for everything, including input validation.
Importantly, exceptions have nothing to do with something being in your control or not. For example, suppose that you have a fairly long and complicated module that uploads a file. There are many fail points in something like that: the file could be too big, the file could be the wrong format, etc. Without exceptions your only option is a lot of if/then checks and some kind of status return at the very end. With exceptions, all you have to do is use a set of cfthrows:
<cfthrow type="FileUpload.TooBig" message="The file size was #FileSize#, but the maximum size allowed is #MaxFileSize#">
<cfthrow type="FileUpload.WrongType" message="The file type was #FilType#, but the accepted types are #AcceptedTypeList#">
Then, whatever is calling the file upload function can catch either with <cfcatch type="FileUpload"> or catch a specific one (e.g. <cfcatch type="FileUpload.WrongType">).
Also, technically a user breaking a password is out of your control, in the sense that the user has determined the value for the password. That said, I loathe password rules as invariably they make it harder, not easier, to maintain security.

How can I intercept uncaught exceptions on Tomcat?

I am trying to figure out a clean way to intercept uncaught exceptions that occur in my application.
I have log4j configured for logging the normal application flow and caught exceptions, so that is taken care of. Right now, I have a class that takes all error-level messages and adds them to a queue to be emailed in batches.
Ideally, I'm hoping that there is a way I can go about intercepting the uncaught exceptions, so that I may pass them to the same 'email batch' queue, but if this is not posible, I'm certainly open to suggestion.
I'm familiar with LogInterceptors on JBoss, but this project is using Tomcat. Is there any way that I might go about this? Is there a LogInterceptor equivelant for Tomcat? Should I try to redirect the Tomcat logging to a custom appender? (If so - any hints on that?) Some other ideas?
I figured that this has to be a solved problem by now, so I am hoping to tap some collective wisdom. Thanks, everyone, in advance.
Per the J2EE 1.4 spec, uncaught exceptions within a servlet may be forwarded to an error page as defined in the deployment descriptor. When this happens, the page implementation will receive the original request and response objects, with the addition of a request attribute named javax.servlet.error.exception that contains the exception object.
That said, I have not actually done this with Tomcat, and most of the web applications that I've worked on forward to a generic error page at the webserver level.
Edit: just tried it out on my local server, after adding the following to my web.xml, and it works as advertised:
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/dumpRequest.jsp</location>
</error-page>
It's not Tomcat-specific, but you can set uncaught exception handlers on a per-thread basis.
Depending on the setup of your application, you could set this at the top of your method that handles a request. You might have to do it every time, as you may get a thread per request.
A good place to set it would be in some sort of front controller.