Home > Mobile >  What is an elegant way to wrap an error an rethrow in both cases?
What is an elegant way to wrap an error an rethrow in both cases?

Time:02-04

There is a method which can:

  1. throw an error
  2. return null

I need to throw a user friendly exception to upper level in the both cases. What is the most elegant way for it? The brute force is:

try {
  result = callMethod();
} catch (SomeException e) {
  throw new UserFiendlyException("cannot process you, try again pls");
}
if (result == null) {
  throw new UserFiendlyException("cannot process you, try again pls");
}

UPD 1: kotlin is accepted and preferable (but I'm also curious how could it be in Java)

UPD 2: Please, don't suggest the use of exceptions for control flow is an anti-pattern: https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why

CodePudding user response:

If callMethod() is your own method, you could update that to perform the null check internally and throw the error...

function callMethod() {
    const responseFromService = null;

    if (responseFromService == null)
        throw new SomeException(`Expected a valid response from the service but got null.`);
}

try {
  result = callMethod();
}
catch (SomeException e) {
  throw new UserFiendlyException("cannot process you, try again pls");
}

You can also try the null coalescing operator...

try {
  result = callMethod() ?: throw new SomeException(`Escape!`);
}
catch (SomeException e) {
  throw new UserFiendlyException("cannot process you, try again pls");
}

Or just keep it simple and check for null within the try...

try {
  result = callMethod();
  if (result == null) throw new SomeException(`Escape!`);
}
catch (SomeException e) {
  throw new UserFiendlyException("cannot process you, try again pls");
}

Edit: Answer originally had the nullish coalescing operator as an option, but the question is for Java, not JavaScript. My bad.

Edit (2): Turns out there is a nullish coalescing operator in Kotlin; option restored.

CodePudding user response:

try...catch and throw are expressions in Kotlin, so you can do:

val result =
    try {
        callMethod()
    } catch (e: SomeException) {
        null
    } ?: throw UserFiendlyException("cannot process you, try again pls")

The try...catch will produce null if either callMethod returns null. or if an exception occurred. We check if it is null using ?:, and if it is, we throw the user friendly exception.

result will end up having a non nullable type.

  •  Tags:  
  • Related