Exception Handling in Kotlin Coroutines Channel fan out - exception

How do I re throw the exception returned from remote call to caller method of handle function ?
suspend fun handle(phMessages: List<PrincipalHierarchyMessage>) {
val messageChannel = Channel<PrincipalHierarchyMessage>()
launchSender(phMessages, messageChannel).invokeOnCompletion {
messageChannel.close()
}
repeat(concurrency) { launchReceiver(messageChannel) }
}
private fun launchSender(phMessages: List<PrincipalHierarchyMessage>, channel: SendChannel<PrincipalHierarchyMessage>) = launch {
phMessages.forEach {
channel.send(it)
}
}
private fun launchReceiver(channel: ReceiveChannel<PrincipalHierarchyMessage>) = launch {
for (msg in channel) {
if (msg.isAddUserToGroup()) {
permsWriterClient.addUserToGroup(msg.groupId, msg.userId, msg.traceId, msg.isLowPriority)
} else if (msg.isRemoveUserFromGroup()) {
permsWriterClient.removeUserFromGroup(msg.groupId, msg.userId, msg.traceId, msg.isLowPriority)
} else {
// log
}
}
}
I have tried calling handle method from a coroutineScope inside try catch, where I expected to catch the exception, but it did not work

Related

Why RuntimeException not stop execution with finally block?

I ask an help to understand why this difference of behavior.
public class Test3 {
public static void main(String[] args) {
Double d = new Test3().findPrice$withoutFinally();
//Double d = new Test3().findPrice$withFinally();
System.out.println(d);
}
private double findPrice$withoutFinally() {
double price = -1.0;
int attempt = 0;
do {
try {
price = getPrice();
}
catch (MyException e) {
System.out.println("Caught MyException!");
}
attempt++;
} while (attempt < 3);
return price;
}
private double findPrice$withFinally() {
double price = -1.0;
int attempt = 0;
do {
boolean retry = false;
try {
price = getPrice();
}
catch (MyException e) {
System.out.println("Caught MyException!");
}
finally {
System.out.println("finally");
if (retry) {
System.out.println("retrying...");
attempt++;
} else {
break;
}
}
} while (attempt < 3);
return price;
}
private Double getPrice() throws MyException {
if (true) {
throw new RuntimeException("Testing RE");
}
return null;
}
}
I mean this, running findPrice$withoutFinally() method I got:
Exception in thread "main" java.lang.RuntimeException: Testing RE
that is the behaviour thah I expect. But running findPrice$withFinally() method I got this unexpected (for me!) behaviour:
finally
-1.0
findPrice$withFinally() should not behave as findPrice$withoutFinally() and then stop execution because of the exception?
Thanks!
finally block is executed ALWAYS - when there is an exception and when there is no exception

Why am I getting "connection refused" error after restart Spark server?

I have this test classes:
class PostIT {
companion object {
#BeforeClass
#JvmStatic
fun initialise() {
baseURI = "http://localhost:4567"
Server.start()
}
#AfterClass
#JvmStatic
fun tearDown() {
Server.stop()
}
}
//some test cases
}
class UserIT {
companion object {
#BeforeClass
#JvmStatic
fun initialise() {
baseURI = "http://localhost:4567"
Server.start()
}
#AfterClass
#JvmStatic
fun tearDown() {
Server.stop()
}
}
//some test cases
}
and Server object:
object Server {
fun start() {
Spark.init()
prepareRoutes()
}
fun stop() {
Spark.stop()
}
private fun prepareRoutes() {
get("/users", whatever)
//more routes
}
}
When I run both test classes separately, it works fine. But, when I tell IDE to run both test classes, I'm getting connection refused error when second test class is run.
It seems like when server is stopped, it never starts again. It's like Spark.init() is not working after server being stopped.
I've also tried calling Spark.awaitInitialization() after Spark.init().
What am I missing?
Solved! Actually, problem wasn't the server initialization after stopped. We must wait until server is stopped. I found the solution here.
fun stop() {
try {
Spark.stop()
while (true) {
try {
Spark.port()
Thread.sleep(500)
} catch (ignored: IllegalStateException) {
break
}
}
} catch (ex: Exception) {
}
}

How to access StackTrace property form my Custom Exceptions in dot net core

I'm trying to implement my own custom exceptions in dot net core.
This is what I have so far:
public class WSException: Exception
{
// some custom stuff...
private readonly string _developerMessage = "";
public string DeveloperMessage { get { return _developerMessage; } }
public WSException() {}
public WSException(string message) : base(message) {
this._developerMessage = message;
}
public WSException(string message, Exception inner) : base(message, inner) {
this._developerMessage = message;
}
public WSException(Exception ex) : base(ex.Message, ex.InnerException) {
_developerMessage = ex.Message;
Source = ex.Source;
//StackTrace = ex.StackTrace; // cannot be assigned to, it's read only
}
public WSException(string message) : base(message) {
this._developerMessage = (String.IsNullOrWhiteSpace(developerMessage) ? message : developerMessage);
}
}
When I catch a general exception, I try to create one of my own (a WSException) to handle it in a common way, like this:
try {
// whatever
}
catch (WSException e) {
HandleException(e);
}
catch (Exception e) {
HandleException(new WSException(e));
}
When I do it like that, e.Source and e.StackTrace are null, and when I try to assign StackTrace I get a Propery or indexer 'Exception.StackTrace' cannot be assigned to --it is read only.
How should such I implement this constructor?
public WSException(Exception ex) : base(ex.Message, ex.InnerException) {
_developerMessage = ex.Message;
Source = ex.Source;
//StackTrace = ex.StackTrace; // cannot be assigned to, it's read only
}
The workaround I found so far is to handle it when I'm serializing the error to json, something like this:
public class WSExceptionJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var ex = value as WSException;
writer.WriteStartObject();
// buch of properties[...]
string stackTrace = null;
if (ex.StackTrace != null) {
stackTrace = ex.StackTrace;
} else if (ex.InnerException != null && ex.InnerException.StackTrace != null) {
stackTrace = ex.InnerException.StackTrace;
} else {
stackTrace = null;
}
writer.WritePropertyName("stacktrace");
serializer.Serialize(writer, stackTrace.Split('\n'));
writer.WriteEndObject();
}
But it feels too hacky

rxjava reactor, Utility to propagate exception

I'm trying to write an utility which automatically propagate checked exception in a reactiv way without writing boiler plate code with static block inside my operators:
public class ReactRethrow {
public static <T, R> Function<T, R> rethrow(Function<T, R> catchedFunc) {
return t -> {
try {
return catchedFunc.apply(t);
} catch (Exception e) {
throw Exceptions.propagate(e);
}
};
}
}
but it stil complaining about IOException here:
Flux.fromArray(resources).map(ReactRethrow.rethrow(resource -> Paths.get(resource.getURI())))
any idea?
Well for a reason I do not clearly understand You have to take as parameter a function which throw exceptions and so declare a specific functionalInterface:
public class ReactRethrow {
public static <T, R> Function<T, R> rethrow(FunctionWithCheckeException<T, R> catchedFunc) {
return t -> {
try {
return catchedFunc.call(t);
} catch (Exception e) {
throw Exceptions.propagate(e);
}
};
}
#FunctionalInterface
public interface FunctionWithCheckeException<T, R> {
R call(T t) throws Exception;
}
}
from here https://leoniedermeier.github.io/docs/java/java8/streams_with_checked_exceptions.html

Exceptions handling trouble

Trying to add divide by zero exception in my calculator project through the try/catch block:
private class Calculate implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
if (operation.equals("/")) {
display.setText(Double.toString(getResult() / Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("*")) {
display.setText(Double.toString(getResult() * Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("-")) {
display.setText(Double.toString(getResult() - Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("+")) {
display.setText(Double.toString(getResult() + Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
if (display.getText().endsWith(".0")) {
display.setText(display.getText().replace(".0", ""));
}
calculationMade = true;
operation = "";
}
catch (IllegalArgumentException exc) {
display.setText("You cannot divide by zero!");
}
}
}
But in this way it still writes me "Infinity" in a text field. Can anybody suggest where i'm wrong please?
When working with double, zero division returns Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY (depending on operand signs)
System.out.println(1.0d/0d);
System.out.println(-1.0d/0d);
System.out.println(1.0d/-0d);
System.out.println(-1.0d/-0d);
Only non-decimal arithmetic throws an exception on zero division. And the exception is not an IllegalArgumentException but an ArithmeticException.