How can I use ResponseEntityExceptionHandler and ErrorController together in Spring Boot 3.2?

18 views Asked by At

I only want to handle errors on Ajax requests with a ResponseEntityExceptionHandler, and errors on page navigations or Form submit requests with an ErrorController.

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    
    @ExceptionHandler({Exception.class})
    @Nullable
    public ResponseEntity<Object> handleAllException(
            Exception ex, WebRequest request) throws Exception {
           //...
        }
        @Override
    @Nullable
    protected ResponseEntity<Object> handleExceptionInternal(
            Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatusCode statusCode, WebRequest request) {
           ResponseEntity<Object> responseEntity = super.handleExceptionInternal(ex, body, headers, statusCode, request);
           //do something
           return responseEntity;
        }
@Controller
public class CommonErrorController implements ErrorController { 
    
    @GetMapping("/error")
    public String handleError(HttpServletRequest request) {
        //do something
        return "/error";
    }

I have defined 2 classes as above, but any errors in the browser's page navigation or when processing the Form Submit will also go through the GlobalExceptionHandler and be returned as json. How can I navigate to the /error page?

0

There are 0 answers