Custom exceptions handling - java Web Services - java

Its my first time posting here so please be patient and correct me whenever necessary...
I am building simple web service-based application using NetBeans with GlassFish. NetBeans does help a lot in terms of generating code for new web services and their operations, one thing drives me mad though - web service exception handling. Operation like:
#WebMethod(operationName = "checkUserExist")
public String checkUserExist(#WebParam(name = "login") String login, #WebParam(name = "password") String password) throws LoginException {
String auth_code = "";
bk_end.Validate val = new bk_end.Validate();
boolean isValidated = val.check(login, password);
if(isValidated)
{
auth_code = val.return_AuthCode();
bank_services.CustomerSerice.setAuth_Code(auth_code);
return auth_code;
}
throw new LoginException("Something is wrong!");
}
and the exception class:
public class LoginException extends Exception
{
String message;
public LoginException(String message)
{
super();
this.message = message;
}
public String getErrorMessage()
{
return this.message;
}
}
throws a massive
Exceptions details : java.lang.reflect.InvocationTargetException
plus tons of other exceptions..
I realise it is a very much so nooby question, but after many hours of trying various things I just do not know what tot do.
I've read about the #WebFault thing but got no idea how to specify this correctly (attach my exception to a particular method..)
Please help, all ideas are more than welcome!
Exceptions that I'm getting:
Service invocation threw an exception with message : null; Refer to the server log for more details
Exceptions details : java.lang.reflect.InvocationTargetException
javax.servlet.ServletException: java.lang.reflect.InvocationTargetException
at org.glassfish.webservices.monitoring.WebServiceTesterServlet.doPost(WebServiceTesterServlet.java:330)
at org.glassfish.webservices.monitoring.WebServiceTesterServlet.invoke(WebServiceTesterServlet.java:106)
at org.glassfish.webservices.EjbWebServiceServlet.service(EjbWebServiceServlet.java:114)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.doFilter(ServletAdapter.java:1002)
at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.invokeFilterChain(ServletAdapter.java:942)
at com.sun.grizzly.http.servlet.ServletAdapter.doService(ServletAdapter.java:404)
...
Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.webservices.monitoring.WebServiceTesterServlet.doPost(WebServiceTesterServlet.java:301)
... 24 more
Caused by: bank_services.LoginException_Exception: excepts.LoginException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilder.java:145)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:123)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:93)
at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:144)
at $Proxy383.checkUserExist(Unknown Source) ... 29 more

Oh ok. You want to see the "Something is wrong" message.
So I think the ultimate problem here is that you are not using the standard detailMessage field in the Throwable. If you just pass the message to the base class (super(message);) then I bet you would see the exception in the trace. Did you try another Exception type such as just Exception?
You could also define the LoginException.toString() to be something like:
#Override
public String toString() {
String s = getClass().getName();
return (message != null) ? (s + ": " + message) : s;
}
Alternatively, you will need to do something like this:
try {
...
} catch (Exception e) {
if (e instanceof ServletException) {
e = e.getCause();
}
if (e instanceof InvocationTargetException) {
e = e.getCause();
}
if (e instanceof LoginException) {
System.err.println("Login exception returned message: "
+ ((LoginException)e). getErrorMessage());
} else {
System.err.println("Exception returned message: " + e);
}
}
But I think my recommendation is to use super(message); in your constructor.

Related

Spring boot wont call my dao [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 4 years ago.
I am getting simple Null pointer exception which I am unable to resolve.
Have tried debugging the application but it just wont go in the dao class where i want it to go. It shows : Unable to Install breakpoint and Absent Line control message. But as i learned from other questions on stack overflow this message was to be ignored ,so that I did.
Details for issue:
Exception :
in test controller
in create Service
at com.service.DesignerService.create(DesignerService.java:20) at
com.controller.HomeController.test(HomeController.java:26) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)in create service java.lang.NullPointerException
My controller method :
#GetMapping("/test")
public String test() {
System.out.println( "in test controller");
DesignerService obj = new DesignerService();
try {
obj.create();
} catch (Exception e) {
e.printStackTrace();
}
return "index";
}
My service calling :
public void create (){
System.out.println("in create service");
Designer designer = getDesigner();
designerDao.createDesigner(designer);
}
And Dao where the debugger never reaches
public void createDesigner(Designer designer) {
Session session = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
String id = String.valueOf(session.save(designer));
System.out.println("Designer ID :"+id);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
}
}
Please help me run this project . Many thanks in advance
Instead of creating a object why don't you Autowire your service using
#Autowired
private DesignerService obj
and where did you initialise this object designerDao

java.lang.RuntimeException: Unable to resume activity with java.lang.IllegalArgumentException

Recently I sometimes got this exception when MainActivity called onResume().
java.lang.RuntimeException: Unable to resume activity {com.qau4d.c35s3.androidapp/com.xxx.XXX.XXX.MainActivity}: java.lang.IllegalArgumentException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3400)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1510)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.IllegalArgumentException
at android.os.Parcel.readException(Parcel.java:1687)
at android.os.Parcel.readException(Parcel.java:1636)
at android.app.ActivityManagerProxy.isTopOfTask(ActivityManagerNative.java:5475)
at android.app.Activity.isTopOfTask(Activity.java:5961)
at android.app.Activity.onResume(Activity.java:1252)
at com.qau4d.c35s3.androidapp.onResume(XActivity.java:29)
at com.qau4d.c35s3.androidapp.onResume(MainActivity.java:196)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6768)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3377)
Both in MainActivity and super class XActivity, only super.onResume(); is called. It's really strange to get this exception after a long time normal development.I checked some relative reference material but nothing got.
In the method Activity#isTopOfTask we can see:
private boolean isTopOfTask() {
if (mToken == null || mWindow == null) {
return false;
}
try {
return ActivityManager.getService().isTopOfTask(getActivityToken());
} catch (RemoteException e) {
return false;
}
}
And in ActivityManagerService#isTopOfTask we can found:
#Override
public boolean isTopOfTask(IBinder token) {
synchronized (this) {
ActivityRecord r = ActivityRecord.isInStackLocked(token);
if (r == null) {
throw new IllegalArgumentException();
}
return r.task.getTopActivity() == r;
}
}
So, I think that ActivityRecord is null.But I don't know why it is null....
There is insufficient information in your question to determine the cause of the java.lang.IllegalArgumentException, Unfortunately the android ActivityThread doesn't log the stacktrace of that exception, and the exception message appears to be empty.
However, it looks like there is a way forward. The exception is handled by the following code in the ActivityThread::performResumeActivity method:
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Unable to resume activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
If you register an Instrumentation class for your activity, it should be possible to use an onException method to log the stacktrace for the causal exception. Another possibility is to use Thread.setUncaughtExceptionHandler to set a handler for the thread in which the IllegalArgumentException is thrown.
These won't solve the problem (!) but it will get you a step closer to a solution.

com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog only on error-catch

So my Java/Spring/CXF/MySQL webservice is up and running, complete with bean validation which throws a custom exception upon error. This all works great.
But what about unanticpated errors (Faults) the service might throw? Like what this page calls "unmodelled faults" , like a failure to connect to the backend database. To this end I deliberately put an incorrect password in my hibernate.properties file.
So I created a custom CXF interceptor to snag the soapfault:
public class MyOutSoapFaultInterceptor extends AbstractSoapInterceptor
{
private static Logger logger = Logger.getLogger( MyOutSoapFaultInterceptor.class);
public MyOutSoapFaultInterceptor()
{
super(Phase.MARSHAL);
}
#Override
public void handleMessage( SoapMessage message) throws Fault
{
logger.debug("entering");
Exception e = message.getContent( Exception.class);
if( e == null) {
logger.debug("e is null");
} else {
logger.debug("e is not null");
logger.debug("e.getCause:" + e.getCause());
logger.debug("e.getMessage:" + e.getMessage());
if( e instanceof Fault) {
logger.debug("e is instanceOf Fault");
SoapFault sf = SoapFault.createFault((Fault) e, message.getVersion());
logger.debug("sf is not null");
logger.debug("sf.getCause:" + sf.getCause());
logger.debug("sf.getMessage:" + sf.getMessage());
logger.debug("sf.getStatusCode:" + sf.getStatusCode());
logger.debug("sf.getCode:" + sf.getCode());
Fault newwFault = new Fault( new Exception("dammit"), Fault.FAULT_CODE_SERVER);
newwFault.setMessage("argh");
throw newwFault;
}
}
}
pertinent part of appclient.xml:
<bean id="formsWebServicePortProxy" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
<property name="wsdlDocumentUrl" value="http://localhost:8080/dept_forms_webservice/formsService?wsdl"/>
<property name="serviceInterface" value="mycom.dept.forms.web.endpoint.FormsEndpoint"/>
<property name="serviceName" value="FormsEndpointImplService"/>
<property name="portName" value="FormsEndpointImplPort"/>
<property name="namespaceUri" value="http://endpoint.web.forms.dept.mycom/"/>
</bean>
and my NON-web client app to test my service contains this snippet:
ApplicationContext ctx = new ClassPathXmlApplicationContext("appclient.xml");
theApp.formsWebServicePortProxy = (FormsEndpoint) ctx.getBean("formsWebServicePortProxy");
logger.debug("entering");
System.out.println("entering testFindAllPermits");
java.util.List<mycom.dept.forms.web.endpoint.Permit> list_permit;
try {
System.out.println("inside try block");
list_permit = formsWebServicePortProxy.findAllPermit(); // <-- error thrown
ListIterator<Permit> iter = list_permit.listIterator();
while( iter.hasNext()) {
System.out.println( iter.next().toString());
}
} catch ( org.springframework.remoting.jaxws.JaxWsSoapFaultException f) {
System.out.println("caught JaxWsSoapFaultException");
f.printStackTrace(); // <-- error thrown here
} catch ( Exception e) {
System.out.println("caught Exception");
System.out.println("e.getCause:" + e.getCause());
System.out.println("e.getMessage:" + e.getMessage());
if( e instanceof FormsEndpointException) {
System.out.println("caught FEE");
}
e.printStackTrace();
}
logger.debug("exiting");
yields the following when attempting to call the method on the webservice:
inside try block
caught JaxWsSoapFaultException
org.springframework.remoting.jaxws.JaxWsSoapFaultException: Error reading XMLStreamReader.; nested exception is javax.xml.ws.soap.SOAPFaultException: Error reading XMLStreamReader.
at org.springframework.remoting.jaxws.JaxWsPortClientInterceptor.doInvoke(JaxWsPortClientInterceptor.java:557)
at org.springframework.remoting.jaxws.JaxWsPortClientInterceptor.invoke(JaxWsPortClientInterceptor.java:541)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy36.findAllPermit(Unknown Source)
at mycom.dept.forms.app.FormsWebServiceClient.testFindAllPermits(FormsWebServiceClient.java:434)
at mycom.dept.forms.app.FormsWebServiceClient.main(FormsWebServiceClient.java:480)
2015-12-02 23:58:55 DEBUG [dept.forms.app.FormsWebServiceClient-testFindAllPermits] - exiting
exiting
Caused by: javax.xml.ws.soap.SOAPFaultException: Error reading XMLStreamReader.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:156)
at com.sun.proxy.$Proxy35.findAllPermit(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.remoting.jaxws.JaxWsPortClientInterceptor.doInvoke(JaxWsPortClientInterceptor.java:580)
at org.springframework.remoting.jaxws.JaxWsPortClientInterceptor.doInvoke(JaxWsPortClientInterceptor.java:554)
... 6 more
Caused by: com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog
at [row,col {unknown-source}]: [1,0]
at com.ctc.wstx.sr.StreamScanner.throwUnexpectedEOF(StreamScanner.java:677)
at com.ctc.wstx.sr.BasicStreamReader.handleEOF(BasicStreamReader.java:2119)
at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2025)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1117)
at com.ctc.wstx.sr.BasicStreamReader.nextTag(BasicStreamReader.java:1140)
at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:139)
at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:61)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:798)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1667)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1520)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1428)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:658)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:532)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:464)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:367)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:320)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:89)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:134)
... 13 more
the root of all seems to be
Caused by: com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog
at [row,col {unknown-source}]: [1,0....
This error turns up a few hits like this page that suggest I'm getting an empty response from the webservice. Or more precisely, an empty Soap body. But googling turns up lots of examples of "throw new Fault( new Exception( "foo"));" Maybe I'm not handling things correctly on the client end?
TIA,
Still-learning Stev

Configuring GWT to return full exceptions to client

When an uncaught exception occurs on the server, the client has the onFailure() method called on the async callback for the service call. He only gets StatusCodeExceptions, which provide little information. I would like to get the actual exception that occurred on the server with its stack trace. Is this possible in GWT?
In my service interface, I added 'throws Exception' to the methods where I want the exception details from the server. This permits me to get the Exception message that occurred on the server, but its stack trace still stops at the client.
I understand that this is not good practice for a production environment, but I would like to enable this for testing.
This will be a three step process.
Set the uncaught exception Handler. In the onModuleLoad() method should be fine.
GWT.setUncaughtExceptionHandler(new ExceptionHandler());
Create a class that will implement the GWT.UncaughtExceptionHandler interface and will parse the Throwable.
public static class ExceptionHandler implements GWT.UncaughtExceptionHandler {
#Override
public void onUncaughtException(final Throwable e) {
if (e instanceof UmbrellaException) {
final UmbrellaException umb = (UmbrellaException) e;
String errMsg = "";
for (Throwable t : umb.getCauses()) {
errMsg += t.getMessage() + "\n";
for (StackTraceElement element : t.getStackTrace()) {
errMsg += element.getClassName() + "(" + element.getMethodName() + ":"
+ element.getLineNumber() + ")\n";
}
/* errMsg String contains full stack trace */
}
}
}
}
Call the ExceltionHandler and pass in the Throwable that came in the onFailure maithod()
new ExceptionHandler().onUncaughtException(caught);
If any exception occurs on the server simply throw the exception object to the client (from the RPC servlet)

Verify Error while invoke static function in playframework controller

I am trying to invoke a static function (Users.dashboard()) at runtime and I am getting a Verify Error exception. Users class inherits CRUD.java and does not take any params.
In Home.index():
public class Home extends Controller {
public static void index() {
for (Class<CRUD> clazz : play.Play.classloader
.getAssignableClasses(CRUD.class)) {
Dashboard d;
try {
Method m = clazz.getMethod("dashboard");
if (m != null) {
d = (Dashboard) m.invoke(clazz.newInstance(), new Object[] {});
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
} catch (Exception e) {
}
}
render(dashboards);
}
Console Output:
#69iahfk3j
Internal Server Error (500) for request GET /home
Oops: VerifyError
An unexpected error occured caused by exception VerifyError: (class: controllers/Home, method: index signature: ()V) Register 1 contains wrong type
play.exceptions.UnexpectedException: Unexpected Error
at play.Invoker$Invocation.onException(Invoker.java:242)
at play.Invoker$Invocation.run(Invoker.java:284)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.VerifyError: (class: controllers/Home, method: index signature: ()V) Register 1 contains wrong type
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
at java.lang.Class.getDeclaredMethods(Class.java:1791)
at play.utils.Java.findActionMethod(Java.java:98)
at play.mvc.ActionInvoker.getActionMethod(ActionInvoker.java:602)
at play.mvc.ActionInvoker.resolve(ActionInvoker.java:85)
... 1 more
Public static methods in controllers are enhanced by Play so invocation on these methods can be problematic.
Did you annotation this method with #Util if it is a utility method ?
If you just wan to redirect to dashboard in this case, you can simply use redirect on the action, something like
redirect("Users.dashboard");

Categories