try implement SQLGrammarException into method Java - java

im trying to implement SQLGrammarException into my method.
This method show me column error, but i need to show what procedure the column with error from.
public static PersistenceMicrodataException dealHibernateException(Throwable e) {
e.printStackTrace();
Throwable t = ExceptionUtil.getCause(e);
return new PersistenceMicrodataException(t.getMessage(), t);
}
I try this:
public static PersistenceMicrodataException dealHibernateException(Throwable e) {
try {
Throwable t = ExceptionUtil.getCause(e);
} catch (Exception e) {
System.out.println(t.getMessage());
System.out.println(((SQLGrammarException) t).getSQLState());
System.out.println(((SQLGrammarException) t).getErrorCode());
System.out.println(t.getCause());
}
return new PersistenceMicrodataException(e.getMessage(), e);
}
Someone can help me with this?

I found solution!
public static PersistenceMicrodataException dealHibernateException(Throwable e) {
String concatError = ((SQLGrammarException) e).getSQL() + ((SQLGrammarException) e).getClass() + ((SQLGrammarException) e).getCause();
while (e != null) {
java.lang.System.out.println(concatError);
break;
}
Throwable t = ExceptionUtil.getCause(e);
return new PersistenceMicrodataException(concatError,t);
}

Related

How to extract try catch outside method?

I have this method sendParameterValueAsMQTTMessage() which I use to publish message via MQTT on a specific topic. I am using try catch two times after another (not nested) but it still seems somewhat ugly and overcrowding the method. I read an article on clean code where Uncle Bob talks about extracting the body of try catch but I seem to not grasp it quite well or at least not in my case.
How could I get rid of the try catch in my method by extracting it outside?
public void sendParameterValueAsMQTTMessage() {
String payload = null;
try {
payload = convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC,payload,0);
try {
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
there are multiple different problems with provided code, here is how I'd refactor it:
public void sendParameterValueAsMQTTMessage() {
final String payload = tryGetPayloadAsJson();
if (payload != null) {
trySendPayloadViaMQTT(payload);
}
}
private String tryGetPayloadAsJson() {
try {
return convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
return null;
}
private void trySendPayloadViaMQTT(final String payload) {
try {
final MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC, payload, 0);
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
one thing which might be improved here based on Uncle Bob's advice is to actually move try/catch outside of trySendPayloadViaMQTT, like this:
public void sendParameterValueAsMQTTMessage() {
final String payload = tryGetPayloadAsJson();
if (payload != null) {
trySendPayloadViaMQTT(payload);
}
}
private String tryGetPayloadAsJson() {
try {
return convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
return null;
}
private void trySendPayloadViaMQTT(final String payload) {
try {
sendPayloadViaMQTT(payload);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
private void sendPayloadViaMQTT(final String payload) {
final MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC, payload, 0);
this.client.publish(message);
Thread.sleep(3000);
}
you can put all of your code in just one try block and set multiple catches, when ever an exception be happened, the catch that is revelated to it will be execute, like:
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
You can use single general catch for both possible exceptions inside the method as following:
public void sendParameterValueAsMQTTMessage() {
String payload = null;
try {
payload = convertToJSONString("range", String.valueOf(range));
MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC,payload,0);
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
public void sendParameterValueAsMQTTMessage() {
String payload = null;
try {
payload = convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC,payload,0);
publishMessage(message); //extracted in a new method
}
public void publishMessage(MQTTMessage message){
try {
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}

Java try-with-resource implementation done by compiler

I was wondering, when exception occurs how try with resource statement manages to close resources before entering catch block.
When exception occurs execution immediately jumps to catch block. So where actually try-with-resource closes the resources.
To get better understanding of how it works I decided to see how compiler implements it. I wrote following code and and compiled it.
public class Test
{
public static void main(final String[] args) {
//I used same JDK for compilation and execution.
System.out.println("Java version: " + System.getProperty("java.version") + "\n");
try(CloseMe me = new CloseMe();
CloseMeToo meToo = new CloseMeToo()){
System.out.println("trying");
throw new Exception("try failed");
} catch(Exception e) {
System.out.println("failed");
System.out.println("\n");
System.out.println(e.getMessage());
System.out.println(e.getSuppressed()[0].getMessage());
System.out.println(e.getSuppressed()[1].getMessage());
}
}
}
class CloseMe implements AutoCloseable {
#Override
public void close() throws Exception {
System.out.println("me closing!");
throw new Exception("don't close me :o");
}
}
class CloseMeToo implements AutoCloseable {
#Override
public void close() throws Exception {
System.out.println("meToo closing!");
throw new Exception("don't close me too :O");
}
}
Output
Java version: 15.0.1
trying
meToo closing!
me closing!
failed
try failed
don't close me too :O
don't close me :o
Then I went to www.javadecompilers.com and tried the decompilers there. Two decompilers gave decent results: CFR 0.150 and Fernflower.
CFR is most readable and complete so posting it here.
public class Test
{
public static void main(final String[] args) throws Throwable{
System.out.println("Java version: " + System.getProperty("java.version") + "\n");
try {
Throwable throwable = null;
Object var2_4 = null; //<-- where this variable is used?
try {
CloseMe me = new CloseMe();
try {
CloseMeToo meToo = new CloseMeToo();
try {
System.out.println("trying");
throw new Exception("try failed");
}
catch (Throwable throwable2) {
throwable = throwable2; //<-- I put this line to make it work
if (meToo != null) {
meToo.close();
}
throw throwable2;
}
}
catch (Throwable throwable3) {
if (throwable == null) {
throwable = throwable3;
} else if (throwable != throwable3) {
throwable.addSuppressed(throwable3);
}
if (me != null) {
me.close();
}
throw throwable;
}
}
catch (Throwable throwable4) {
if (throwable == null) {
throwable = throwable4;
} else if (throwable != throwable4) {
throwable.addSuppressed(throwable4);
}
throw throwable;
}
}
catch (Exception e) {
System.out.println("failed");
System.out.println("\n");
System.out.println(e.getMessage());
System.out.println(e.getSuppressed()[0].getMessage());
System.out.println(e.getSuppressed()[1].getMessage());
}
}
}
I understand decompilers have limitations. Ideal decompiler would've given me same try-with-resource back and I wouldn't have seen these details. So it is ok.
My questions are:
In above decompiled code, variable var2_4 is unused. Also, I had to add a line to make it work like try-with-resource. I think the code is not complete. If there are any, can you add/explain missing parts?
If anyone, who understands bytecode, translate class file to exact java code would be great. Or give me pointers about where can I get the tools to do the job.
Thank you!
The behavior of try-with-resources is fully documented in the Java Language Specification, section 14.20.3. try-with-resources.
It specifically shows that the following abbreviated version of the question code:
try (CloseMe me = new CloseMe(); CloseMeToo meToo = new CloseMeToo()) {
System.out.println("trying");
} catch (Exception e) {
System.out.println("failed");
}
first gets converted to:
try {
try (CloseMe me = new CloseMe(); CloseMeToo meToo = new CloseMeToo()) {
System.out.println("trying");
}
} catch (Exception e) {
System.out.println("failed");
}
then to:
try {
final CloseMe me = new CloseMe();
Throwable #primaryExc1 = null;
try (CloseMeToo meToo = new CloseMeToo()) {
System.out.println("trying");
} catch (Throwable #t) {
#primaryExc1 = #t;
throw #t;
} finally {
if (me != null) {
if (#primaryExc1 != null) {
try {
me.close();
} catch (Throwable #suppressedExc) {
#primaryExc1.addSuppressed(#suppressedExc);
}
} else {
me.close();
}
}
}
} catch (Exception e) {
System.out.println("failed");
}
then to:
try {
final CloseMe me = new CloseMe();
Throwable #primaryExc1 = null;
try {
final CloseMeToo meToo = new CloseMeToo()
Throwable #primaryExc2 = null;
try {
System.out.println("trying");
catch (Throwable #t) {
#primaryExc2 = #t;
throw #t;
} finally {
if (meToo != null) {
if (#primaryExc2 != null) {
try {
meToo.close();
} catch (Throwable #suppressedExc) {
#primaryExc2.addSuppressed(#suppressedExc);
}
} else {
meToo.close();
}
}
}
} catch (Throwable #t) {
#primaryExc1 = #t;
throw #t;
} finally {
if (me != null) {
if (#primaryExc1 != null) {
try {
me.close();
} catch (Throwable #suppressedExc) {
#primaryExc1.addSuppressed(#suppressedExc);
}
} else {
me.close();
}
}
}
} catch (Exception e) {
System.out.println("failed");
}

How to regroup catch finally into one method in java 8?

New to java 8, I would like to optimise my code bellow:
public Response create() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
public Response update() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
I have a lot of methods using this same way to catch exceptions and do the same finally, is that possible to replace the bellow common code by a method in java 8? So that I could optimise all my methods who use this common code.
} catch (Exception e) {
codeA;
} finally {
codeB;
}
Depends what you do in the .... You could do something like this:
private Response method(Supplier<Response> supplier) {
try{
return supplier.get();
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
and invoke like:
public Response create() { return method(() -> { ... for create }); }
public Response update() { return method(() -> { ... for update }); }
You could wrap your payload and put it to the separate method. One thing; what do you expect to return on exception catch. This time this is null, but probably you could provide default value.
public static <T> T execute(Supplier<T> payload) {
try {
return payload.get();
} catch(Exception e) {
// code A
return null;
} finally {
// code B
}
}
Client code could look like this:
public Response create() {
return execute(() -> new CreateResponse());
}
public Response update() {
return execute(() -> new UpdateResponse());
}
This could be a generic solution.
//here describe supplier which can throw exceptions
#FunctionalInterface
public interface ThrowingSupplier<T> {
T get() throws Exception;
}
// The wrapper
private <T> T callMethod(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (Exception e) {
//code A
}finally {
// code B
}
}

Non-Static Generic function that invokes a method passed in as a parameter

I'm trying to consolidate 2 methods into 1, because they handle exceptions the same way. I know in C# you can pass functions/actions as parameters into other functions. I tried creating a generic method to invoke a function, but can't seem to figure it out.
public String getTheStuff(String client) {
try {
return extService.getProduct(client);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
public CustomType getsomeMoreStuff(String source, int offset) {
try {
return extService.getMetrics(source, offset);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
What I'm looking for is something like
public T invokeExtService(Function functionToInvoke, Parameters[] params){
try {
return functionToInvoke.Invoke(params);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
As #LouisWasserman said, this would be much nicer in Java 8, but how about something like this (untested):
public <T> T invoke(Callable<T> function) {
try {
return function.call();
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
public String getTheStuff(final String client) {
return invoke(new Callable<String>() {
#Override
public String call() {
return extService.getProduct(client);
}
});
}
public CustomType getsomeMoreStuff(final String source, final int offset) {
return invoke(new Callable<CustomType>() {
#Override
public CustomType call() {
return extService.getMetrics(source, offset);
}
});
}
To be honest, I'm not sure how worthwhile this is considering how short your methods are (and they could be even shorter with multi-catch).

Handling iBatis NestedSQLException

I have a java app that try to insert a row into the table and com.​ibatis.​common.​jdbc.​exception.NestedSQLException is thrown with the Cause com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException
When I try to insert dublicate data for a unique-key constraint.
How do I catch that exception?
To get to the root cause you can do something like this:
try {
//insert
} catch (NestedSQLException e) {
Throwable t = e;
while(t.getCause() != null) {
t = t.getCause();
}
//in your situation, now t should be MySQLIntegrityConstraintViolationException
if (t instanceOf MySQLIntegrityConstraintViolationException) {
//do something
}
}
In case it helps someone. #tibtof's is correct and got me to:
public int insert(MyObject myObject) {
int recCount = -1;
try {
recCount = insert(myObject, MyObjectMapper.class);
} catch (Throwable e) {
Throwable t = e;
while (t.getCause() != null) {
t = t.getCause();
if (t instanceof SQLIntegrityConstraintViolationException) {
// get out gracefully.
recCount = -1;
return recCount;
}
}
//Something else wicked wrong happened.
LogUtils.error(log, e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
return webGroup.getWebGroupId().intValue();
}

Categories

Resources