how to catch an exception inside a scala future' s callback onCompelete Success case? - concurrency

I have a future and sending that value to the caller actor my problem is I am calling future.onCompelete and inside its case Success callback I am getting an exception I want to know what is the right way to catch that exception as the Failure block will not work in this use case
here is my code
val future = Futute{calling a http route which sends back a response}
future.onComplete {
case Success (response) => //do some processing with response got some exception while doing this
throw new RunTimeException("got exception while working the response")
sender() ! response
case Failure (ex) => ex.printStackTrace
}
in the above code, I am unable to catch the exception I only got AskTimeOutException when i am calling this future code
I can only catch the exception if I surround it with try-catch
like this
val future = Futute{calling a http route which sends back a response}
future.onComplete {
case Success (response) => //do some processing with response got some exception while doing this
try {
throw new RunTimeException("got exception while working the response")
sender() ! response
}
catch {
case ex:Exception(e)=>log.error("got an exception",ex)
}
case Failure (ex) => ex.printStackTrace
}
is this the right approach to do this? or is there any better way to do this?

In general, onComplete shouldn't be used if you care about an exception thrown in the callback (nor should the other Unit-returning method which needs an (implicit) ExecutionContext: foreach).
The most general approach and the most similar to onComplete is to use transform (or its cousin transformWith: transform is to transformWith as map is to flatMap), for example
future.transform {
case Success(response) =>
// these are both equivalent... the exception will get wrapped into a failed future
Failure(new RuntimeException("BOOM!"))
throw new RuntimeException("BOOM!")
case f # Failure(ex) =>
ex.printStackTrace()
f // pass-through
}

Related

bloc handleError does not catch error in dart

So I am using the flutter_bloc plugin and I want to throw an exception for invalid states.
#injectable
class MyBloc extends Bloc<MyEvents, MyStates> {
MyBloc();
#override
MyStates get initialState => MyStates.initial();
#override
Stream<MyStates> mapEventToState(MyEvents event) async* {
throw Exception();
}
}
then I want to unit test whether the exception was thrown. I always get an unhandled error exception despite me using the handleError wrapper and the anything matcher. How to I catch this error?
expectLater(bloc.handleError((err, _) => print(err)), emits(anything));
The error message is
Unhandled error Exception occurred in bloc Instance of 'MyBloc'.
From Felix Angelov's answer here: https://github.com/felangel/bloc/issues/815
you can just let the exception bubble up by not wrapping the code in a
try/catch and then you can use blocTest with errors to verify an error
occurred.
blocTest(
'CounterBloc throws Exception when null is added',
build: () async => CounterBloc(),
act: (bloc) => bloc.add(null),
errors: [
isA<Exception>(),
]
);
Hope that helps 👍
Thank you so much :) it is exactly what I was looking for :)

Symfony3 and PHP 7 return type decleration for Doctrine Repository methods

I really like PHP's return type declarations, and I want to use it on Symfony 3.
All controller methods should return a Response object, no problem there. But in Doctrine repositories though, Doctrine might return an Entity object, or null.
Consider this example:
You have created a simple Post entity.
You have created a custom findByName method in PostRepository:
PostRepository.php
public function findByName($name) : Post
{
$qb = $this->createQueryBuilder('p')
->where('p.name = :name')
->setParameter('name', $name);
$post = $qb->getQuery()->getOneOrNullResult();
return (null === $post) ? new Post() : $post;
}
You call this method from a controller, like this:
DefaultController.php
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('AppBundle:Post');
try {
$post = $repository->findByName('test');
} catch (\TypeError $e) {
$post = new Post();
}
return new Response(dump($post));
}
I am aware trying to catch exception won't execute because findByName() always returns a Post object.
My question is, where should we handle the exception? According to this answer, it is better to throw an exception. Should we ensure repository method does not throw an exception at all by using this:
$post = $qb->getQuery()->getOneOrNullResult();
return (null === $post) ? new Post() : $post;
or let PHP throw a TypeError exception and let controller handle it?
Doctrine, throws exceptions for getOneOrNullResult() and getSingleResult() methods as described here.
If this scenario doesn't make sense because it's better to let your controller handle the exception and return a "not found" page because post doesn't exist like this:
return $this->createNotFoundException();
Scenario #2
Post exists in the database, and another repository method is called, getApprovedComments(), no comments are returned, we're expecting an ArrayCollection but we get an array. This will throw PHP's TypeError exception.
I think code is going to be full of try/catch blocks. Is it ok to handle this kind of exceptions at a higher level to have less try/catch blocks in code?
At a second thought this is not the best solution, because code should be flexible enough to catch every TypeError exception and take proper action on how to render the page.

Akka Ask Pattern on future recover

I'm writing a Spray + Akka small server. And a blog post stood out and recommended this ask pattern. The CapserOk class has a signiture of this:
case class CasperOk(company: Option[Company.Company], existOrNot: Boolean)
I'm retrieving this database row and if it doesn't exist or some error occured, I want to send out a response from Spray to tell the client.
However, using this pattern, I don't know where to inject the switch.
I tried to change the code to this:
val response = (secCompanyActor ? jObjectFromCasper(company))
.mapTo[CasperOk]
.map(result => result.succeedOrNot match {
case true => (OK, "transaction successful")
case false => (Conflict, "FileLoc format is wrong or it already exists")
})
.recover{case _ => (InternalServerError, "error occured! We will fix this")}
complete(response)
Spray uses complete() to send out a HTTP response. complete() can either take two objects, or a string/serializable object. I want to use the two object mode (which allows me to manually encode its header), and an ideal situation should look like complete(response._1, response._2)
Is there any way to achieve this with Akka's Future?
You can achieve this via registering a call to complete function on future onComplete method.
response.onComplete {
case (statusCode, message) => complete(statusCode, message)
}

Return untranslated results from a Play!2 WS call (in Scala)

I'm writing a play Controller that should call another web service and return its result verbatim -- same response code, same headers, same body. But it seems like the Controller is written such that I have to specify an explicit return code. I've tried getting the ahcResponse, but that doesn't seem to provide an obvious solution.
Here's what I have now:
def route(name: String, command: String) = Action {
Async {
(
WS.url("someurl").get().map {
(
response => Ok(response.body))
})
}
}
However, this always returns an "OK" status, and if it gets an error, it will pull the error HTML into the body as text.
How do I forward the results of a WS call back to my caller?
You could forward the response code and body in the following way:
WS.url(url)
.get
.map(response =>
response.status match {
// in case you want to do something special for ok
// otherwise, pattern matching is not necessary
case OK => Ok(response.body)
case x => new Status(x)(response.body)
})
.recover {
case ex: Throwable =>
InternalServerError("some exception...")
}

Axis2 : Handling Userdefined Exceptions

I am seeing Exception handling in Apache Axis2 Webservices .
My Skelton class throws a Userdefined Exception named as "NoUserFound" , which in have configured inside WSDL file
Inside my skelton class
public samples.quickstart.xsd.GetPriceResponse getPrice(
samples.quickstart.xsd.GetPrice getPrice0)
throws GetSolutionByIdFault {
samples.quickstart.xsd.GetPriceResponse response = new samples.quickstart.xsd.GetPriceResponse();
response.set_return("Hi");
String value = (String) getPrice0.getSymbol();
if (value.equals("Pavan"))
throw new GetSolutionByIdFault("name not present");
return response;
}
Inside my client class , i am handling this in this way :
try {
// Some Logic here
}
catch (AxisFault er) {
er.getMessage();
}
catch (Exception e) {
e.printStackTrace();
}
So when ever a user defined exception is thrown for example (GetSolutionByIdFault) , i am handling it in the AxisFault block .
is this the correct approach ??
Yes, that looks fine - if you want, you catch more specific exceptions as well...
It depends on what you have to do in order to handle the exception. If you need to do special things according to the backend exception then you need to catch each and every exception and handle them separately.
Normally I used to handle exceptions separately.