英文:
How to return a custom error page in SpringBoot's asynchronous processing
问题
关于SpringBoot中的错误处理,我有一个问题。
在使用@Async注解的方法中发生异常时,是否有办法显示自定义错误页面?如果有的话,我很想知道。
我们目前正在SpringBoot中实现异步处理。
异步处理在以下方法中进行概述。我在这里遇到的问题是,Spring的SimpleAsyncUncaughtExceptionHandler会代替自定义的ExceptionHandler捕获异常。
服务类。
@Service
@Slf4j
public class MyService {
...
@Async
public void myAsyncMethod(Integer req) throws MyException {
if (req > 500) {
log.error("请求过大。" + req);
throw new MyException();
}
...
hogehoge(req);
}
}
ExceptionHandler类
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler
@ResponseStatus(HttpStatus.FORBIDDEN)
public ModelAndView handleMyException(MyException e) {
log.error(e.getMessage());
return new ModelAndView("4xx.html");
}
}
MyException类(用于测试)
public class MyException extends Exception {
}
英文:
I have a question about error handling in SpringBoot.
Is there a way to display a custom error page when an exception occurs in a method annotated with @Async? I'd be happy to know if there is any.
We are currently implementing asynchronous processing in SpringBoot.
Asynchronous processing is outlined in the following methods. I'm having trouble with Spring's SimpleAssyncUncaughtExceptionHandler instead of the custom ExceptionHandler catching it.
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
@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)
public class MyException extends Exception {
}
答案1
得分: 0
这可以部分地通过使用DeferredResult来解决。
这个问题通过从Handler类传递DeferredResult并使用setErrorResult()来临时解决。
英文:
It turns out that this can be solved in part by using DeferredResult.
This was tentatively resolved by passing a DefferdResult from the Handler class and doing setErrorResult().
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论