0

I'm new to scala so I might not be clear with the issue I'm facing, I'll do my best to clarify.

In an existing codebase, there is a servlet, with a post method (org.scalatra.ScalatraBase), similar to:

val myPost: Route = post("/endpoint/", operation(myoptions)) {

If the logic in this function throws a RuntimeException, the response is serialized using the exception's toString method

I want to convert my code to asyncPost (org.scalatra.AsyncSupport), similar to:

val myPost: Route = asyncPost("/endpoint/", operation(myoptions)) {

now if the logic in this function throws the same exception, I get:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"> 
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="keywords" content="error"/>
    <title>Unexpected Failure</title>
    <style type="text/css">
...

The code looks like:

    val response = for {
      myMagic <- doMagic(parsedBody) // returns Try[Magic] <- exception thrown here is serialized correctly
      newMagic = moreMagic(myMagic) // returns Future[MoreMagic] <- exception thrown here is converted to that html response
    } yield newMagic

    response.fold(
      fa => fa,
      fb => for {
        ha <- fb
      } yield someMoreMagic(ha)
    )
}
Navnav
  • 982
  • 3
  • 11
  • 25
  • 3
    Well I have zero experience with **Scalatra**, but I guess a first step is not to mix `Try` and `Future`, and even less create a `Try[Future]`, lift the first `Try` into a `Future` using `Fututre.fromTry` then compose everything inside `Future` using a `for` - Then, I may suggest using methods like `recoverWith` to handle the error but not sure how those play with the framework. – Luis Miguel Mejía Suárez May 10 '23 at 12:27
  • 1
    I have the same lack of experience as @LuisMiguelMejíaSuárez about `Scalatra`, but as he said, don't mix `Future` and `Try` using a `for` (also known as `for-comprehension`/`for-yield`). It's just a syntax sugar for `flatMap`, `withFilter` and `map`. In other functional languages is also called `do notation`. Here you have a thread in SO that give more details about [for-comprehenion, flatMap and map](https://stackoverflow.com/a/14602182/7214091) – Gastón Schabas May 10 '23 at 13:36

0 Answers0