how to handle nested exception in java? - jdbc

I am trying to connect to mysql database. I am using try catch while establishing connection.
I want that I should be able to know what exception was caught, so that, I can show appropriate error message.
e.g if I pass incorrect hostname, i should show Wrong hostname provided.
One way to do is get class name of runtime exception class. but nested exception is being thrown like this..
There was some error while establishing connection to the
databasecom.mysql.jdbc.CommunicationsException: Communications link
failure due to underlying exception:
-- BEGIN NESTED EXCEPTION -- java.net.UnknownHostException MESSAGE:
localhsost STACKTRACE: java.net.UnknownHostException: localhsost at
java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) at
java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:867) at
java.net.InetAddress.getAddressFromNameService(InetAddress.java:1246)
at java.net.InetAddress.getAllByName0(InetAddress.java:1197) at
java.net.InetAddress.getAllByName(InetAddress.java:1128) at
java.net.InetAddress.getAllByName(InetAddress.java:1064) at
com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:246)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:271) at
com.mysql.jdbc.Connection.createNewIO(Connection.java:2771) at
com.mysql.jdbc.Connection.(Connection.java:1555) at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:620) at
java.sql.DriverManager.getConnection(DriverManager.java:222) at
accessMySQL.accessMySQL.createConnection(accessMySQL.java:24) at
test.main(test.java:16)
-- END NESTED EXCEPTION -- Last packet sent to the server was 1 ms
ago. Problem in establishing connection.
Now I would like to know that class name UnknownHostException, so I can setup a condition like
if(e.getClass().toString() == "UnknownHostException")
System.out.println("Exception caught while connection to database. Hostname appears to be incorrect");
please help !!
P.s that typo in hostname is deliberately there to generate exception

Try this:
if (e.getCause() instanceof UnknownHostException) {
// ...
}

Related

Grails/Spring Web Flow Plugin: Session must not be null error

I'm trying to run a flow (Grails 2.3.11, Spring Web Flow 2.0.8.1, JDK 1.7.0_21, OS X 10.9.4).
The first time I fire up the application (by typing "grails run-app" on the command line), I can get to the first page of the flow, and the flow seems to work normally.
However, the next time I try to execute the flow, I get the error below (from the console). This happens even when I delete my cookies and restart the application. If I leave it for a few days and come back to it, it seems to work again (the first time only).
I found a thread from six years ago, but I am not calling flow.clear() like the original poster was. My flow code is below.
Does anyone have any insights on this?
Error:
[ERROR] 27 Jul 2014 21:54:14,086 org.springframework.webflow.engine.impl.FlowExecutionImpl FlowExecutionListener threw exception
java.lang.NullPointerException
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:191)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
[ERROR] 27 Jul 2014 21:54:14,096 org.codehaus.groovy.grails.web.errors.GrailsExceptionResolver IllegalArgumentException occurred when processing request: [GET] /inscriba/author/createAuthor - parameters:
execution: e1s2
Session must not be null. Stacktrace follows:
org.springframework.webflow.execution.FlowExecutionException: Exception thrown in state 'headshot' of flow 'author/createAuthor'
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:191)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalArgumentException: Session must not be null
... 5 more
Code:
def createAuthorFlow = {
log.debug("createAuthorFlow: I am here: ")
create {
log.debug("create: I am here")
on("next") {
log.debug("create.next: I am here")
flow.author = new Author(params)
!flow.author.validate() ? error() : success()
flow.author.save()
}.to "headshot"
}
headshot {
on("next") {
log.debug("headshot.next: I am here")
}.to "summary"
}
summary()
}
I believe the problem is that you have to use Serializable objects in order to put them into the flow scope. My guess is that the Author object doesn't implement Serializable.
The Grails web-flow documentation mentions this, but just says that an "exception" will be thrown. It took me quite a while to figure out what was going on - hope this helps.

checking for specific error code in PL/SQL exception block

I am getting the ORA-06503: PL/SQL: Function returned without value error in a pl/sql trigger code. I actualy want to do some specific exception handling only if this error occurs else do the regular exception handling in my code.
My question is how do I capture the specific ORA codes in exception blocks. Like If I want to add a if condition like
If(oracode = something) then ...
else ...
the SQLERRM gives the ora code with error message. how do I use this in IF condition ?
Need help with this
Thanks.
You are looking for SQLCODE - these are negative numbers when there is an error.
if SQLCODE = -6503 then ....

Exception raised when invoking MembershipUser.ResetPassword() using OracleMembershipProvider

In some cases, MembershipUser.ResetPassword() raises an exception. This only happens for some users, and it's not clear why. There are no inputs to the method, so it seems like a problem internal to Oracle's membership provider implementation.
The exception text: The provider returned an error that is not described by other MembershipCreateStatus enumeration values.
The traceback:
at Oracle.Web.Security.OracleMembershipProvider.ResetPassword(String username, String passwordAnswer)
at System.Web.Security.MembershipUser.ResetPassword(String passwordAnswer)
at System.Web.Security.MembershipUser.ResetPassword()
...
Any idea what could be happening here?
Today I were having the same issue.
Answer is very simple. User account is LOCKED. Execute MembershipUser.UnlockUser() before password reset.

jqgrid error Status: 'error'. Error code: 500 on add more meaningful message

I have a jqgrid which works fine. However there is a constraint in my database and I need to provide more meaningful validation method when adding.
The problem is when I submit the dialog shows the error: error Status: 'error'. Error code: 500
I would much prefer it to show the actual error caused by the exception thrown on save:
Violation of UNIQUE KEY constraint 'UKC_InvoiceId_ActivityId'. Cannot insert duplicate key in object 'dbo.InvoiceLine'. The duplicate key value is (11, 1). The statement has been terminated.
Can anybody tell me how to achieve this?
If you use ASP.NET then you can use try {...} catch (SqlException ex) {...} block over the code which implement the row insertion. You can analyse ex.Procedure, ex.Server, ex.LineNumber, ex.Message values inside of the SqlException and generate (throw) another exception with more readable message. You can use in the error message the texts typed by the user and explain which data the user have to modify to solve the problem.

Custom oracle exceptions through JDBC

In a stored procedure I have used to;
raise_application_error (-20010, 'My Message');
to raise a custom error in a certain situation. What I am trying to do is when I make my JDBC call from java, to be able to identify this error as not just being a SQLException so that I can handle it differently. I though I could identify it by the errorCode, but that seems to always be 17062 and not -20010.
Is there another way to do this, or am I missing something?
you should get 20010 as your errorCode. the ORA-17062 is an error for invalid ref cursors. Are you sure the procedure you are calling throws the custom error ?

Resources