简体   繁体   English

SpringBoot的异步处理中如何返回自定义错误页面

[英]How to return a custom error page in SpringBoot's asynchronous processing

I have a question about error handling in SpringBoot.我有一个关于 SpringBoot 中错误处理的问题。 Is there a way to display a custom error page when an exception occurs in a method annotated with @Async?有没有办法在使用@Async 注释的方法中发生异常时显示自定义错误页面? I'd be happy to know if there is any.我很高兴知道是否有。

We are currently implementing asynchronous processing in SpringBoot.我们目前正在 SpringBoot 中实现异步处理。 Asynchronous processing is outlined in the following methods.以下方法概述了异步处理。 I'm having trouble with Spring's SimpleAssyncUncaughtExceptionHandler instead of the custom ExceptionHandler catching it.我遇到了 Spring 的 SimpleAssyncUncaughtExceptionHandler 而不是捕获它的自定义 ExceptionHandler 的问题。

Service Class.服务类。

@Service
@Slf4j
public class MyService {
     ...
     @Async
     public void myAsyncMethod(Intger req) throws MyException {
         if (req > 500) {
             log.error("request too large." + req);
             throw new MyException();
         }
         ...
         hogehoge(req);
     }
} 

The ExceptionHandler class ExceptionHandler 类

@ControllerAdvice
public class ExceptionController {
     
     @ExceptionHandler
     @RespondeStatus(HttpStatus.FORBIDDEN)
     public ModelAndView handleMyException(MyException e) {
         log.error(e.getMessage());
         return new ModelAndView("4xx.html");
     }
}

MyException class (for testing) MyException 类(用于测试)

public class MyException extends Exception {
}

It turns out that this can be solved in part by using DeferredResult.事实证明,这可以通过使用 DeferredResult 部分解决。 This was tentatively resolved by passing a DefferdResult from the Handler class and doing setErrorResult().通过从 Handler 类传递 DefferdResult 并执行 setErrorResult() 暂时解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM