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

huangapple go评论69阅读模式
英文:

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().

huangapple
  • 本文由 发表于 2020年8月24日 13:58:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63555468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定