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.
Related
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
}
I am using Grails 4.0.3 and want to assert that an exception is thrown in a given situation. Below, my PidService.
def validatePidIssuingConclusionDocument(JSONObject pidIssuingConclusionDocument){
String message = "Document issuing number is mandatory"
if(!pidIssuingConclusionDocument.has("docIssuingNumber")){throw new Exception(message)}
}
Below, my test case:
void "wrong document"() throws Exception {
JSONObject documentWithoutIssuingNumber = new JSONObject()
documentWithoutIssuingNumber.accumulate("docIssuingNumber","123")
pidService.buildPidIssuingOrder(documentWithoutIssuingNumber)
// How can I assert that the exception is thrown and verify it message.
}
I tried to use try/catch in the test case without success. Could anyone help me? I need to assert that the exception is thrown and the message is Document issuing number is mandatory in the given case.
I need to assert that the exception is thrown and the message is
Document issuing number is mandatory in the given case.
I can't provide an executable example around the code you provided because some things are missing (like buildPidIssuingOrder). See the project at https://github.com/jeffbrown/dnunesexception which contains an example that shows a way to deal with the exception in a test though.
grails-app/services/dnunesexception/PidService.groovy
package dnunesexception
import org.grails.web.json.JSONObject
class PidService {
def buildPidIssuingOrder(JSONObject pidIssuingConclusionDocument) {
throw new Exception('Document issuing number is mandatory')
}
}
src/test/groovy/dnunesexception/PidServiceSpec.groovy
package dnunesexception
import grails.testing.services.ServiceUnitTest
import spock.lang.Specification
import org.grails.web.json.JSONObject
class PidServiceSpec extends Specification implements ServiceUnitTest<PidService>{
void "test something"() {
when:
JSONObject documentWithoutIssuingNumber = new JSONObject()
documentWithoutIssuingNumber.accumulate("docIssuingNumber","123")
service.buildPidIssuingOrder(documentWithoutIssuingNumber)
then:
def e = thrown(Exception)
and:
e.message == 'Document issuing number is mandatory'
}
}
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 :)
I need save the source code of failed test to fix it. How to get the source html while using codeception test in yii 2?
I cannot get $I->grabPageSource() and $I->_getResponseContent() to work though there are these exact functions.
public function checkCall(FunctionalTester $I)
{
$I->amOnRoute('mx/ed',['model' => 'State']);
$I->seeResponseCodeIs(200);
$I->seeResponseCodeIsSuccessful();
$html = $I->grabPageSource();
}
Codeception saves page source of last request for all failed tests in tests/_output directory by itself, there is nothing for you to do.
Failed assertion throws exception so your code after $I->seeResponseCodeIsSuccessful is not executed.
If you want to implement some custom error handling in specific test, you can wrap assertions in try-catch block and grabPageSource inside catch.
public function checkCall(FunctionalTester $I)
{
$I->amOnRoute('mx/ed',['model' => 'State']);
try{
$I->seeResponseCodeIs(200);
$I->seeResponseCodeIsSuccessful();
} catch (Exception $e) {
$html = $I->grabPageSource();
//do your error handling here
throw $e; //rethrow exception to make test fail
}
}
If you want to implement custom error handling for all tests, add _failed method to Helper\Functional class in tests/_support/Helper directory.
public function _failed(\Codeception\TestInterface $test, $fail)
{
$testName = $test->getMetadata()->getName();
$pageSource = $this->getModule('Yii2')->getPageSource();
//do your error handling here
}
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.