如何处理 Spring Boot 中 DeferredResult 中的异常?

How to handle exception in DeferredResult in Spring Boot?

我有一个休息方法:

@RequestMapping(value = "wash/washHistory", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    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(() -> {
                final String result = washController.getWashHistory( managerId, order, sortType, limit, offset);
                defResult.setResult(result);            
        }).start();
    return defResult;
    }

在 "getWashHistory" 中,我抛出以下自定义异常:

throw new InvalidUserInputException("Wrong offset", this.getClass().getSimpleName(), "getWashHist", params);

为了处理这个异常,我使用了以下 class:

@ControllerAdvice
@EnableWebMvc
public class GlobalExceptionHandler {
 @ExceptionHandler(value = InvalidUserInputException.class)
    public ResponseEntity<String> invalidUserInputExc(InvalidUserInputException e) {
          logger.log("GMoika", e.error().getClassName(), e.error().getMethodName(), e.error().getParams(), e.error().getCause());
        return ResponseEntity.
                status(HttpStatus.BAD_REQUEST).
                body(e.error().getErrorCode());  
    }
}

只要我不使用DeferredResult就可以正常工作,但是当我想使用非阻塞方式时,会出现超时异常。 我找到了一种修复方法:

defResult.onTimeout(new Runnable() {
        @Override
        public void run() {
            defResult.setErrorResult("Explanation goes here.");
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); //or SC_NO_CONTENT
        }
    });

但这不是我要找的,因为我用特定的构造函数抛出自己的异常,以便在 class 中写入引发此异常的地方。 在我的 GlobalExceptionHandler class?

中是否有任何其他可能的方法来处理 DeferredResult 中的异常

DeferredResult 有方法 setErrorResult 可以接受异常并根据 documentation:

The value may be an Exception or Throwable in which case it will be processed as if a handler raised the exception.

@jny 的决定在大多数情况下都是正确的,但对我来说,我找到了另一种方法 在我的休息控制器中,我添加了以下代码:

new Thread(() -> {          
            Thread.currentThread().setUncaughtExceptionHandler(new SeparateThreadsExceptionHandler(defResult));
            final String result = washController.getWashHistory(managerId, order, sortType, limit, offset);
            defResult.setResult(result);
        }).start();

还有一个 SeparateThreadsExceptionHandler 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 {
            dr.setResult(UnknownException.UNKNOWN_ERROR_CODE);
        }
    }

}

当我的自定义异常被抛出时,我可以将一些字符串错误消息设置为 DeferredResult。在我的示例中,它是前端的错误代码。

Is there any other possible ways to handle exceptions in DeferredResult in my GlobalExceptionHandler class

我使用了@jny

指出的setErrorResult方法

这是我的控制器方法的主体:

DeferredResult<Wrapper<Object>> deferredResult = new DeferredResult<>();

ForkJoinPool.commonPool().submit(() -> {
    try {
        Wrapper<Object> response = ...
        deferredResult.setResult(response);
    } catch (Exception e) {
        deferredResult.setErrorResult(e);
    }
});

return deferredResult;

在这种情况下,新线程中抛出的异常被传递给全局@ExceptionHandler