Skip to content

ErrorPageFilter ignores REST response in case of Exception #2745

@damienpolegato

Description

@damienpolegato

I'm running a Spring Boot web app with Thymeleaf + Spring MVC with a mix of MVC and REST calls (from JS code).
In a @ControllerAdvice I have the following exception handling code :

@ExceptionHandler(MyRuntimeException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody MyRestResponse handleMyRuntimeException(MyRuntimeException exception) {
    return new MyRestResponse("Some data I want to send back to the client.");
}

Running Spring Boot with Tomcat embedded container I receive a MyRestResponse object in my ajax failure handler as expected but when I deploy in standalone Tomcat the response is ignored as the ErrorPageFilter forward the exception info instead due to the following code in doFilter() :

if (status >= 400) {
    handleErrorStatus(request, response, status, wrapped.getMessage());
    response.flushBuffer();
}

I went around the problem by writing directly the response to the output stream.

@ExceptionHandler(RuntimeException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public void handleRuntimeException(HttpServletRequest request, HttpServletResponse response, RuntimeException exception) {
        try {
            jacksonMessageConverter.write(new MyRestResult(translateMessage(exception)), MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
            response.flushBuffer(); // Flush to commit the response
            } catch (IOException e) {
            e.printStackTrace();
        }
    }

That solution is ok for me but I think that should be possible to return a @ResponseBody in case of an error happening during a REST call.
I have also tried to return a ResponseEntity as suggested by @rstoyanchev here but still see the same issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: blockerAn issue that is blocking us from releasing

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions