简体   繁体   中英

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

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 {
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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