Why does `ScopedValue.where(SCOPE_VALUE, val).call()` throw Exception?

Josiah Noel josiahnoel at gmail.com
Thu Mar 23 02:52:14 UTC 2023


Hello there,

I'm trying to rewrite one of my job's web applications to use Scoped Values
instead of ThreadLocal, but I've hit a minor inconvenience. Using the run
method works great, but in the case where I want to return the result to my
webserver, I'm forced to deal with the checked exception. I can't use
throws because the endpoints are registered via lambda and so cannot throw
any checked exceptions.

To me, the errors should ideally be handled by my registered error handler
classes to return 500 errors, not for every endpoint to individually define
error logic.

Is there a specific reason that call() throws the checked exception, but
not run()?

What I currently do to avoid.

```
  @Get("/path")
  public Response getStuff(Context ctx) {
   // mdc is populated by the before filters
    final var context = MDC.getCopyOfContextMap();
    MDC.clear();

    try {
      final AtomicReference<Response> resultRef = new AtomicReference<>();
      ScopedValue.where(SCOPE, context)
          .run(
              () -> {
                final var request =
                    new Request(ctx.queryParamMap(), ctx.headerMap(), ctx);

                validator.validate(request);

               // in the service layer a bunch of virtual threads are made
to orchestrate API calls with SC
               // I want to use Scope Values to share the context.
                 resultRef.set( service.getAggregateData(requests));
              });
      return resultRef.get();
    } finally {
      // this gets cleared in the response filter
      MDC.setContextMap(context);
    }
  }
```

What I'd like to do.

```
  @Get("/path")
  public Response getStuff(Context ctx) {
    final var context = MDC.getCopyOfContextMap();
    MDC.clear();

    try {

      return ScopedValue.where(SCOPE, context)
          .call(
              () -> {
                final var request =
                    new Request(ctx.queryParamMap(), ctx.headerMap(), ctx);

                validator.validate(request);
                return service.getAggregateData(requests);
              });

    } finally {
      MDC.setContextMap(context);
    }
  }
```
--
Cheers, Josiah.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20230322/a3b9961d/attachment-0001.htm>


More information about the loom-dev mailing list