0

I have the following method in my rest controller

 public DeferredResult<String> getWashHistory(@RequestParam(value = "sid", required = true, defaultValue = "") String sid,
            HttpServletResponse response, HttpServletRequest request,
            @RequestParam(value = "sort", defaultValue = "") String sortType,
            @RequestParam(value = "order", defaultValue = "") String order,
            @RequestParam(value = "limit", defaultValue = "") String limit,
            @RequestParam(value = "offset", defaultValue = "") String offset) {

        System.out.println("Thread: " + Thread.currentThread());
        final Integer managerId = checkSession(sid);
        DeferredResult<String> defResult = new DeferredResult<>();
        new Thread(() -> {
            System.out.println("tert: " + Thread.currentThread());
            Thread.currentThread().setUncaughtExceptionHandler(new SeparateThreadsExceptionHandler(defResult));
            final String result = washController.getWashHistory(managerId, order, sortType, limit, offset);
            defResult.setResult(result);
        }).start();
        return defResult;
    }

Inside getWashHistory , i throw my custom exception named InvalidUserInputException,to handle this exception I have the following class

public class SeparateThreadsExceptionHandler implements Thread.UncaughtExceptionHandler{
    private DeferredResult<String> dr;
    public SeparateThreadsExceptionHandler(DeferredResult<String> dr){
        this.dr = dr;
    }
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if(e instanceof InvalidUserInputException){
           InvalidUserInputException throwableException =  (InvalidUserInputException)e;
            dr.setResult(throwableException.error().getErrorCode());
        } else {
            throw new UnknownException("Unknown exception", "unKnown", "unKnown", null);
        }

The question is, in project i have a lot of custom exceptions , is it possible to avoid using instance of in public void uncaughtException(Thread t, Throwable e) to switching between all exceptions?

Almas Abdrazak
  • 3,209
  • 5
  • 36
  • 80

1 Answers1

0

You can use inheritance for this as shown below

class ParentException extends Exception {
      // based on .error() call showin in example, I am assuming you have some 
      // class that holds error code.
      private Error error;
}

then child exception will be

class InvalidUserInputException extends ParentException {
// create constructor here that builds Error.
}

and finally,

if(e instanceof ParentException) {
    ParentException throwableException =  (ParentException)e;
            dr.setResult(throwableException.error().getErrorCode());
 }
Yogesh Badke
  • 4,249
  • 2
  • 15
  • 23