Throw exception from closure - dart

I've been trying to setup a simple Serversocket and I would like to have an exception thrown (other than some other stuff ie. setting a var to false) if some error is encountered, it works using an external callback but what about closures?
The Dart editor gives me an error and refuses to run it!
Server(String address,int port,int backlog)
{
this.s = new ServerSocket(address,port,backlog);
this.s.onError = (e) => throw new Exception(e);
}
I've tried also "throw e" and stuff like that, but as long as "throw" is present the ide won't run it.

I have had the same problem, Dart seams to be unable to accepts throws in single line closures. You should be able to do:
Server(String address,int port,int backlog)
{
this.s = new ServerSocket(address,port,backlog);
this.s.onError = (e) {
throw new Exception(e);
};
}
I have not looked in the spec so I don't know if its intentional or is a bug.

Related

Q: Using Circuit Breaker in SAP Cloud SDK resilience

When I tried to use ResilienceDecorator.executeCallable() to enable circuit breaker, I have to throw out ResilienceRuntimeException in my callable to make the circuit break work. Sample code as below. Without it, circuit breaker is always closed. is this the right way to do it?
response = ResilienceDecorator.executeCallable(() -> {
HttpResponse response1 = tryHttpClient.get().execute(request);
if (response1.getStatusLine().getStatusCode() == 404){
throw new ResilienceRuntimeException("404 error is raised when calling SB api");
}
return response1;
},
ResilienceConfiguration.of(SubscriptionBillingAdapter.class).isolationMode(ResilienceIsolationMode.TENANT_OPTIONAL).timeLimiterConfiguration(ResilienceConfiguration.TimeLimiterConfiguration.of().timeoutDuration(Duration.ofSeconds(6L))).circuitBreakerConfiguration(ResilienceConfiguration.CircuitBreakerConfiguration.of().waitDuration(Duration.ofSeconds(600000L)).failureRateThreshold(1).closedBufferSize(1).halfOpenBufferSize(1)),
e -> {LOG.warn("resiliience fallback call: " + e); return response1;});
I am asking since I don't see any document of it. Also when I check how destination configuration in SCP is retrieved, I saw the following code in com.sap.cloud.sdk.cloudplatform.connectivity.DestinationService . It doesn't throw out ResilienceRuntimeException, when using ResilienceDecorator.executeCallable(). so my question is do I need to throw out ResilienceRuntimeException or not to make circuit breaker work? if I don't need, anything wrong in my code?
return (String)ResilienceDecorator.executeCallable(() -> {
XsuaaCredentials xsuaaCredentials = (new ServiceCredentialsRetriever()).getClientCredentials("destination");
AccessToken accessToken;
if (propagateUser) {
accessToken = xsuaaService.retrieveAccessTokenViaUserTokenExchange(xsuaaCredentials.getXsuaaUri(), xsuaaCredentials.getCredentials(), useProviderTenant);
} else {
accessToken = xsuaaService.retrieveAccessTokenViaClientCredentialsGrant(xsuaaCredentials.getXsuaaUri(), xsuaaCredentials.getCredentials(), useProviderTenant);
}
return this.fetchDestinationsJson(servicePath, accessToken);
}, ResilienceConfiguration.of(DestinationService.class).isolationMode(ResilienceIsolationMode.TENANT_OPTIONAL).timeLimiterConfiguration(TimeLimiterConfiguration.of().timeoutDuration(Duration.ofSeconds(6L))).circuitBreakerConfiguration(CircuitBreakerConfiguration.of().waitDuration(Duration.ofSeconds(6L))));
Steven
I'm not the most experienced in this specific part, but looking at your code it seems fine to me. When a server returns 404 Not found it's not an indication of a service failure or error, but that resource is simply not found. If in your case 404 means that an error took place and the request has to be retried with a resilient approach, you have to throw that exception to inform Resilience4J that smth went wrong.
While we're working on improving our documentation, I recommend you take a look at the existing tutorial explaining resilience within the SAP Cloud SDK context. There we also throw ResilienceRuntimeException for clarity:
public List<BusinessPartner> execute() {
return ResilienceDecorator.executeSupplier(this::run, myResilienceConfig, e -> {
logger.warn("Fallback called because of exception.", e);
return Collections.emptyList();
});
}
private List<BusinessPartner> run() {
try {
return businessPartnerService
.getAllBusinessPartner()
.select(BusinessPartner.BUSINESS_PARTNER,
BusinessPartner.LAST_NAME,
BusinessPartner.FIRST_NAME,
BusinessPartner.IS_MALE,
BusinessPartner.IS_FEMALE,
BusinessPartner.CREATION_DATE,
BusinessPartner.TO_BUSINESS_PARTNER_ADDRESS
.select(BusinessPartnerAddress.CITY_NAME,
BusinessPartnerAddress.COUNTRY,
BusinessPartnerAddress.TO_EMAIL_ADDRESS
.select(AddressEmailAddress.EMAIL_ADDRESS)
)
)
.filter(BusinessPartner.BUSINESS_PARTNER_CATEGORY.eq(CATEGORY_PERSON))
.orderBy(BusinessPartner.LAST_NAME, Order.ASC)
.top(200)
.execute(destination);
} catch (ODataException e) {
throw new ResilienceRuntimeException(e);
}
}
Regarding the code snippet from the DestinationService, I believe that fetchDestinationsJson() method throws an implicit exception thus letting Resilience4J know that smth went wrong. While in your case HttpClient won't throw anything when receiving 404 as it's a correct response code as any other.
I also think that checking CircuitsBreaker examples from Resilience4J library might be helpful.
I hope it helps:)
No you do not have to throw a ResilienceRuntimeException. In fact the SDK only uses that to wrap checked and unchecked exceptions into an unchecked exception which wraps all kinds of failures that occur within a resilient call.
Please expand your question with more details, I'll then expand this answer:
Which version of the SDK are you using?
How (and how often) do you invoke the decorated callable? Please expand the code block.
Please specify the exact behaviour you observe. What exception is thrown when you invoke the decorated callable? If the circuit breaker opens this should be a CallNotPermittedException wrapped inside a ResilienceRuntimeException
Reduce the callable to simply throw an exception in order to simplify the code
Reduce the resilience configuration to only use a circuit breaker (leverage ResilienceConfiguration.empty()). If that works add stuff back in again until it doesn't.
For reference also please find the documentation of resilience4j which the SDK uses under the hood to perform resilient operations.

Avoid exception causes to stop Mono.zip immediately

Is it possible to avoid that if one mono in mono.zip throws exception all other monos are stopping immediately? I want them to end normally and perhaps to handle the erroneous one by something like „.doOnError“ or „.continueOnError. Is that a way to go?
Regards
Bernado
Yes, it's possible. You can use Mono.zipDelayError. As you can understand from the method's name, it delays errors from the Monos. If several Monos error, their exceptions are combined.
If you have to get the combined result anyway, zipDelayError is not the solution. Use the zip operator and handle the error case with a fallback operator like onErrorResume or retry on the zipped Mono or any upstream one.
I stated that my question is answered but it is not yet. The following example states my case: some mono will fail, but i want the result as the error too. i expected the follwoing code as to run to completion but it fails:
Mono<String> error = Mono.error(new RuntimeException());
error = error.onErrorResume(throwable -> Mono.just("hell0"));
Mono<String> test = Mono.just("test");
Mono<String> test1 = Mono.just("test1");
Mono<String> test2 = Mono.just("test2");
List<Mono<String>> monolist = new ArrayList<>();
monolist.add(test);
monolist.add(test1);
monolist.add(test2);
monolist.add(error);
Mono<Long> zipDelayError = Mono.zipDelayError(monolist, arrayObj -> Arrays.stream(arrayObj).count());
System.out.println(zipDelayError.block());

catch any error in angular dart (like angular's ErrorHandler)

I need to catch any front end (angulardart) error and send it back to the server.
I saw there is something like his in regular Angular ErrorHandler, but I can't find any equivalent in angular dart (or dart it self).
Maybe I should hack the Exception object's constructor, but I don't find it a good approach (assuming it's possible)
any hints please?
In Dart it's quite similar:
#Injectable()
class ErrorHandler implements ExceptionHandler {
ApplicationRef _appRef;
ErrorHandler(Injector injector) {
// prevent DI circular dependency
new Future<Null>.delayed(Duration.ZERO, () {
_appRef = injector.get(ApplicationRef) as ApplicationRef;
});
}
#override
void call(dynamic exception, [dynamic stackTrace, String reason]) {
final stackTraceParam = stackTrace is StackTrace
? stackTrace
: (stackTrace is String
? new StackTrace.fromString(stackTrace)
: (stackTrace is List
? new StackTrace.fromString(stackTrace.join('\n'))
: null));
_log.shout(reason ?? exception, exception, stackTraceParam);
// We can try to get an error shown, but don't assume the app is
// in a healthy state after this error handler was reached.
// You can for example still instruct the user to reload the
// page with danger to cause hare because of inconsistent
// application state..
// To get changes shown, we need to explicitly invoke change detection.
_appRef?.tick();
}
}
Provide the error handler
return bootstrap(AppComponent, [const Provide(ExceptionHandler, useClass: ErrorHandler)]);
For errors that might be caused outside Angular, see also How to catch all uncaught errors in a dart polymer app?

Grails (2.3) #Transactional does not rollback

Rollback is done here as expected:
#Transactional(propagation = Propagation.REQUIRES_NEW)
def test1() {
def dummy = new Dummy(name: "test1")
dummy.save()
throw new RuntimeException("test1!")
}
But here not - which is probably wrong - try/catch should not affect the behavior:
#Transactional(propagation = Propagation.REQUIRES_NEW)
def test2() {
def dummy = new Dummy(name: "test2")
dummy.save()
try {
throw new RuntimeException("test2!")
} catch (all) {
println all.message
}
}
By default, #Transactional wraps the method such that any non-checked exception (viz., a RuntimeException) will cause the transaction to be rolled back.
If you catch/handle the exception within the method, of course, the exception doesn't propagate up to the transactional wrapper and the transaction won't be marked as rollback-only. This appears to be what you're doing.
It's worth pointing out that you can indicate that the transactional wrapper should rollback transactions if other Exceptions are thrown (and propagate to the wrapper). You can do this with the rollbackFor annotation parameter.
For example,
#Transactional(rollbackFor=Throwable.class)
void doTransactionalWork() throws MyException { ... }
will cause the transaction to be rolled back if any Throwable propagates up to the wrapper, even those that are checked (viz., MyException)
This should be the behavior of any #Transactional method, regardless of whether you're creating a new transaction or inheriting an existing transactional context.
maybe you have misunderstood the purpose of try catch or maybe you are just having a wobbly moment:
#Transactional(propagation = Propagation.REQUIRES_NEW)
def test2() {
//you may be doing other stuff here
//but now about to do some transaction work
//so lets wrap this method around a try catch
try {
//this is happening
def dummy = new Dummy(name: "test2")
dummy.save()
} catch (Exception all) { // or catch (Throwable all) {
// if something went wrong in above save method
//should be caught and runtime exception means roll back
throw new RuntimeException("test2!" +all?.toString())
}
}
I hope it explains where you went wrong but really you wish to do all of this in a service and do the try catch part in the controller -
so you do you transaction work and if things go wrong you may wish to throw additional exceptions from the service that the try catch in the controller would capture and set it to roll back.
I did a sample project years back here hope it helps
eitherway those are someone's experiments and aren't really the way you would go about doing proper coding, I mean it is a rather odd unusual way of doing things and in short he is just trying to make it throw a runtime exception therefore triggering roll back. I stick with my suggestion in the answer that you want to do a one off try catch in the controller. That attempts to capture both validation errors of the object at hand as well as failures within the failure of any given service transactional work. Something like this but probably a lot more work to capture all specific issues and return back to originating page with the underlying issues - having also now rolled back transaction.

How to handle errors while using Glib.Settings in Vala?

I am using Glib.Settings in my Vala application. And I want to make sure that my program will work okay even when the schema or key is not available. So I've added a try/catch block, but if I'm using the key that doesn't exist, the program segfaults. As I understood, it doesn't even reach the catch statement.
Here is the function that uses settings:
GLib.Settings settings;
string token = "";
try
{
settings = new GLib.Settings (my_scheme);
token = settings.get_string("token1");
}
catch (Error e)
{
print("error");
token = "";
}
return token;
And the program output is:
(main:27194): GLib-GIO-ERROR **: Settings schema 'my_scheme' does not contain a key named 'token1'
Trace/breakpoint trap (core dumped)
(of course I'm using my real scheme string instead of my_scheme)
So can you suggest me where I'm wrong?
I know this is super late, but I was looking for the same solution so I thought I'd share one. As #apmasell said, the GLib.Settings methods don't throw exceptions—they just abort instead.
However, you can do a SettingsSchemaSource.lookup to make sure the key exists first. You can then also use has_key for specific keys. For example,
var settings_schema = SettingsSchemaSource.get_default ().lookup ("my_scheme", false);
if (settings_schema != null) {
if (settings_schema.has_key ("token1")) {
var settings = new GLib.Settings ("my_scheme");
token = settings.get_string("token1");
} else {
critical ("Key does not exist");
}
} else {
critical ("Schema does not exist");
}
The methods in GLib.Settings, including get_string do not throw exceptions, they call abort inside the library. This is not an ideal design, but there isn't anything you can do about it.
In this case, the correct thing to do is fix your schema, install into /usr/share/glib-2.0/schemas and run glib-compile-schemas on that directory (as root).
Vala only has checked exceptions, so, unlike C#, a method must declare that it will throw, or it is not possible to do so. You can always double check the Valadoc or the VAPI to see.

Resources