How to handle exception java exception in Flex..? - java

I have made the WSDL from java code using the Xfire framework,
Here is my java code..
public class Test implements TestException {
public void testException(String check) {
List<String> list = new ArrayList<String>();
list.add("ABC");
list.add("XYZ");
list.add("PQR");
list.add("LMNOP");
list.add("EFGH");
list.add("Pqrst");
try
{
if(check(list,check))
System.out.println(check);
}
catch (MyException e)
{
e.printStackTrace();
}
}
public boolean check(List<String> list,String check) throws MyException {
if(list.contains(check))
return true;
else
throw new MyException();
}
}
The exception class is :
public class MyException extends Exception {
public MyException()
{
}
public String toString()
{
return "Exception by My Exception.....";
}
}
*The flex code : *
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600">
<mx:WebService id="testService" wsdl="http://localhost:9090/ExceptionTest/xfire/Test?wsdl" showBusyCursor="true">
<mx:operation name="testException" result="testExceptionRH(event)" fault="testExceptionFH(event)"/>
</mx:WebService>
<mx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
protected function click_clickHandler(event:MouseEvent):void
{
testService.testException(showText.text).send;
}
protected function testExceptionRH(event : ResultEvent) : void
{
messageLbl.text = "No Exception.....!!!!";
}
protected function testExceptionFH(event : FaultEvent) : void
{
trace(event.fault.faultDetail);
messageLbl.text = "Exception.....!!!!";
}
]]>
</mx:Script>
<mx:Button x="163" y="70" label="Click" id="click" click="click_clickHandler(event)"/>
<mx:TextInput x="114" y="27" id="showText"/>
<mx:Label id="messageLbl" fontWeight="bold" x="183" y="99"/>
Now the problem is whenever i am send the object other than object in list say "Amit" then it throw exception right, & so the fault message has to displayed but i am getting always the result handler message, I have check the logs of tomcat it shows exception (MyException) stack trace,
What wrong i am doing ..???
Please help, Thanks in Advance

you already caught the exception in your testException method so it was not propagated to your flex front end.
you should handle the exception (e.g. do your logging) in your catch block then throw it again.
try {
// do work...
} catch (Exception e) {
// handle exception
e.printStackTrace();
// include the root cause and propagate the exception to flex
// using RuntimeException as an example)
throw new RuntimeException("error msg here", e);
}

Related

Using Vert.x handle errors thrown in request middleware

Say I have some middleware and an error is raised:
public class JWTHandler implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
throw new Error("How can I capture this error and send a response.")
ctx.next();
}
}
How can I capture it using some error-handling middleware? Here is a global error handler but it can't reference any request/response pair.
vertx.createHttpServer()
.exceptionHandler(ctx -> {
// I cannot access the request that may have caused the error here
log.error("In the exception handler.");
log.error(ctx.getCause());
})
the only thing I can guess, is something like this:
public class ErrorHandler implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
try{
ctx.next();
}
catch(Exception e){
ctx.response().end("We messed up.");
}
}
}
but I doubt that idea is right? What's the right way to do this?
perhaps one or both of these is sufficient?
router.route().failureHandler(ctx -> {
ctx.response().end("We failed here!");
});
router.route().last().handler(ctx -> {
ctx.response()
.setStatusCode(404)
.end("404 - route/resource could not be found.");
});
I think, the correct approach would be to use the ctx.fail(), when throwing an exception
public class JWTHandler implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
ctx.fail(new Error("How can I capture this error and send a response.");
}
}
And then you can add a failerHandler and access to the Exception with ctx.failure()
router.route().failureHandler(ctx -> {
ctx.response().end(
ctx.failure().getMessage()
);
});
EDIT:
the failureHandler also catches exceptions that are thrown like you did:
public class JWTHandler implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
throw new Error("How can I capture this error and send a response.")
ctx.next();
}
}

RxJava error handling withought swallowing the error

I'm a little bit new to RxJava. I am trying to emit another item if onError() get called without losing the error(I still want onError() to be called on the observer). but when I'm implementing each of the error handling methods declared in the docs the error being swallowed and on error isn't being called. any solutions?
edit:
that's what I've tried to do yesterday -
#Override
public Observable<ArrayList<Address>> getAirports() {
return new Observable<ArrayList<AirportPOJO>>() {
#Override
protected void subscribeActual(Observer<? super ArrayList<AirportPOJO>> observer) {
try {
// get airports from api list and map it
ArrayList<AirportPOJO> airportsList = apiDb.getAirportsList(POJOHelper.toPOJO(AppCredentialManager.getCredentials()));
observer.onNext(airportsList);
} catch (Exception e) {
e.printStackTrace();
observer.onError(handleException(e));
}
}
}.map(AirportsMappers.getAirportsPojoToDomainAirportsMapper()).doOnNext(new Consumer<ArrayList<Address>>() {
#Override
public void accept(ArrayList<Address> airportsList) throws Exception {
// if airports loaded from api - save them to local db
if (airportsList != null) {
try {
localDb.saveAirportList(AirportsMappers.getAirportsToLocalDbAirportsMapper().apply(airportsList));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).onErrorResumeNext(new Function<Throwable, ObservableSource<? extends ArrayList<Address>>>() {
#Override
public ObservableSource<? extends ArrayList<Address>> apply(final Throwable throwable) throws Exception {
// load the local airports -
ArrayList<LocalDbAirportEntity> localAirportsEntities = localDb.getAirports();
// map
ArrayList<Address> airports = AirportsMappers.getLocalDbAirportsToAirportsMapper().apply(localAirportsEntities);
// return the concat observable with the error
return Observable.just(airports).concatWith(Observable.
<ArrayList<Address>>error(new Callable<Throwable>() {
#Override
public Throwable call() throws Exception {
return throwable;
}
}));
}
});
}
today I tought I might doing it wrong and tried -
#Override
public Observable<ArrayList<Address>> getAirports() {
ArrayList<Observable<ArrayList<Address>>> observables = new ArrayList<>();
observables.add(apiDb.getAirportsList(POJOHelper.toPOJO(AppCredentialManager.getCredentials())).map(AirportsMappers.getAirportsPojoToDomainAirportsMapper()));
observables.add(localDb.getAirports().map(AirportsMappers.getLocalDbAirportsToAirportsMapper()));
Observable<ArrayList<Address>> concatenatedObservable = Observable.concatDelayError(observables);
return concatenatedObservable;
}
but I've got the same result. the onNext() called with the data of the second observable and the onError() not being called afterwards.
Resume with the desired value concatenated with the original error:
source.onErrorResumeNext(error ->
Observable.just(item).concatWith(Observable.<ItemType>error(error))
);

Custom Exception Dispatcher in Spring Boot Application for response logic

I have a Spring Boot application that has the following approximate structure:
project
Api
ApiImpl
Application
Api is an interface that looks like this:
public interface Api {
public String methodOne(...) throws ExceptionOne, ExceptionTwo, ExceptionThree;
...
public int methodN(...) throws ExceptionOne, ExceptionThree, ExceptionFour;
}
ApiImpls is the request controller (in reality there is a second layer, but this should suffice for this example). There, I do something like the following right now:
#Controller
public class ApiImpl {
public String methodOne(...) {
try {
// do stuff that can yield an exception
}
catch(ExceptionOne e) {
// set proper response code and return values
}
catch(ExceptionTwo e) {
// set proper response code and return values
}
catch(ExceptionThree e) {
// set proper response code and return values
}
}
}
Basically, this behaviour yields a lot of repetition (might as well name my exceptions D, R, and Y...), but is otherwise very suited to handling the internal application logic.
My question is: How can I implement a custom Exception Dispatcher that would handle this in Java? Ideally, I would want something like this answer here, but unfortunately simply throwing the current exception like in that C++ code is not possible in Java, as far as I know. For brevity, what I would like to accomplish is something like the following:
#Controller
public class ApiImpl {
public String methodOne(...) {
try {
// do stuff that can yield an exception
}
catch(ExceptionOne e) {
handle()
}
}
private void handle() { // maybe Throwable or Exception subclass as parameter
// handle the correct exception type, set correct response code, etc.
}
}
Are there any good approaches to doing this so as to minimize code repetition?
Here is a preliminary attempt I tried to get this working:
public class Thrower {
public Thrower(int e) throws ExceptionOne, ExceptionTwo, ExceptionThree {
if(e == 0) {
throw new ExceptionOne();
}
if(e == 1) {
throw new ExceptionTwo();
}
if(e == 2) {
throw new ExceptionThree();
}
}
}
class ExceptionOne extends Exception {}
class ExceptionTwo extends Exception {}
class ExceptionThree extends Exception {}
public class ExceptionHandler {
private void handle(Exception ex) throws Exception {
try {
throw ex;
}
catch(ExceptionOne e) {
e.printStackTrace();
System.out.println("Exception one");
}
catch(ExceptionTwo e) {
e.printStackTrace();
System.out.println("Exception two");
}
catch(ExceptionThree e) {
e.printStackTrace();
System.out.println("Exception three");
}
}
public void causesException(int which) throws Throwable {
try {
Thrower t = new Thrower(which);
}
catch(Exception e) {
handle(e);
}
}
public static void main(String[] args) throws Throwable {
ExceptionHandler eh = new ExceptionHandler();
eh.causesException(0);
eh.causesException(1);
eh.causesException(2);
}
}
This works as expected, and I can handle the different exception types as needed (shown here using a constructor, but the principle would be the same). However, this feels extremely clunky.
If you are looking for globally handling all Controller Layer exceptions (in Spring MVC architecture), you can do that at one place for all controllers (option1 below) by using #ExceptionHandler methods which is a ControllerAdvice from Spring.
Option(1): Configure Exceptions in Separate Class
#ControllerAdvice
class MyProjectExceptionHandler {
#ExceptionHandler(value = ExceptionOne.class)
public R exceptionOne(ExceptionOne exe) {
//set proper response code and return values
}
#ExceptionHandler(value = ExceptionTwo.class)
public R exceptionTwo(ExceptionTwo exe) {
//set proper response code and return values
}
}
Option(2): Configure Exceptions in Controller Class itself
If you are looking for handling the exceptions within the Controller class itself, then you can do that as below:
#Controller
public class ApiImpl {
public String methodOne(...) {
}
#ExceptionHandler(ExceptionOne.class)
public R exceptionTwo(ExceptionOne exe) {
//set proper response code and return values
}
//other exceptions
}
You can look more on this at here

How to catch exception in Join point which was thrown from #Around

Following up with this comment of my previous question. I'm trying to throw an exception from the #Around advice, and catch it within the callee class and/or method. But I'm getting this error:
Stacktraces
java.lang.Exception: User not authorized
com.company.aspect.AuthorizeUserAspect.isAuthorized(AuthorizeUserAspect.java:77)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:616)
...
The Aspect code is:
#Aspect
public class AuthorizeUserAspect {
#AuthoWired
private UserService service;
#Pointcut("#annotation(module)")
public void authorizeBeforeExecution(AuthorizeUser module) {}
#Around(value = "authorizeBeforeExecution(module)", argNames="module")
public Object isAuthorized(ProceddingJoinPoint jp, AuthorizeUser module) throws Throwable {
// Check if the user has permission or not
service.checkUser();
if ( /* User has NOT permission */ ) {
throw new MyCustomException("User not authorized"); // => this is line 77
}
return jp.proceed();
}
}
and the Struts's based UI action code is:
#Component
public class DashboardAction extends ActionSupport {
#Override
#AuthorizeUser
public String execute() {
...
}
private void showAccessDenied() {
...
}
}
The question is How or Where I can catch that exception to execute showAccessDenied()?
To handle uncaught exceptions like MyCustomException you need to define a global exception handler in Struts 2. Please check this guide: http://struts.apache.org/2.3.4.1/docs/exception-handling.html
For user interface I'd recommend writing a short code for catching any uncaught exceptions.
class EventQueueProxy extends EventQueue {
#Override
protected void dispatchEvent(AWTEvent newEvent) {
try {
super.dispatchEvent(newEvent);
} catch (Throwable t) {
String message = t.getMessage();
if (message == null || message.length() == 0) {
message = "Fatal: " + t.getClass();
}
JOptionPane.showMessageDialog(null, message, "Unhandled Exception Caught!", JOptionPane.ERROR_MESSAGE);
}
}
}
And then in the ui class:
public static void main(String args[]) {
EventQueue queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
queue.push(new EventQueueProxy());
//your code goes here...
}
Note, it will show the dialog window with an error information each time uncaught exception appears. This is just the suggestion for your ui, for the particular case of your ploblem, do use try for firing method(s) that authorizes a user and catch for firing method(s) that should be executed if the user is not authorized. in such case authorization method should throw an exception if an authorization fails. Then the error will not be printed but the particular method will be fired instead.
That's what I'd add to your code:
#Component
public class DashboardAction extends ActionSupport {
#Override
try {
#AuthorizeUser
public String execute() {
...
}
} catch (Exception e) {
private void showAccessDenied() {
...
}
}
}

What kind of exception to manually throw from an Axis web service?

I have some webservices that are developed on axis 1.1, and I need to make a few changes. During this I am fixing up the exception handling code, but I don't know what kind of exception I should throw when there is an error.
I only need to send the message to the client, I don't need to worry about stack traces and custom information in the exceptions. I don't want to deal with extending soapfaults, or providing reasons for the failures, and all that jazz.
#WebMethod
public string[] myMethod() throws ..?.. {
throw new AxisFault(); // not recommended
throw new SOAPFaultException(); // seems overly general
throw new Exception(); // what we have now
}
Is there any right way to do this, or is throw new Exception the right way to go about it?
You may create a custom exception (say FooException) extending Exception annotated with JAX-WS #WebFault.
#WebFault(faultBean = "org.foo.bar.FooFault")
public class FooException extends Exception {
private FooFault fooFault;
public FooException() {
super();
}
public FooException(String message, FooFault fooFault, Throwable cause) {
super(message, cause);
this.fooFault = fooFault;
}
public FooException(String message, FooFault fooFault) {
super(message);
this.fooFault = fooFault;
}
public FooFault getFaultInfo() {
return fooFault;
}
}
// this is org.foo.bar.FooFault
public class FooFault {
// POJO
}
And then you declare that your web method throws that exception.
#WebMethod
public string[] myMethod() throws FooException {
// do some stuff
throw new FooException();
// or with a cause
try {
// something dangerous
} catch (Exception e) {
throw new FooException("Shit happens", new FooFault(), e);
}
// or like this
throw new FooException("Foo", new FooFault());
}
JAX-WS should do the rest.

Categories

Resources