Empty Exception Body in Spring MVC Test

这一生的挚爱 提交于 2019-12-01 15:50:18

After opening a ticket for the issue, I was told that the error message in the body is taken care of by Spring Boot which configures error mappings at the Servlet container level and since Spring MVC Test runs with a mock Servlet request/response, there is no such error mapping. Further, they recommended me to create at least one @WebIntegrationTest and stick to Spring MVC Test for my controller logic.

Eventually, I decided to go with my own custom exception handler and stick to MockMvc for the rest as before.

@ControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public @ResponseBody
    ExceptionResponse handle(HttpServletResponse response, Throwable throwable) {
        HttpStatus status = Optional
                .ofNullable(AnnotationUtils.getAnnotation(throwable.getClass(), ResponseStatus.class))
                .map(ResponseStatus::value)
                .orElse(HttpStatus.INTERNAL_SERVER_ERROR);
        response.setStatus(status.value());
        return new ExceptionResponse(throwable.getMessage());
    }

}

@Data
public class ExceptionResponse extends AbstractResponse {

    private final long timestamp = System.currentTimeMillis();

    private final String message;

    @JsonCreator
    public ExceptionResponse(String message) {
        checkNotNull(message, "message == NULL");
        this.message = message;
    }

}

This likely means that you either didn't handle the exception or you've really left the body empty. To handle the exception either add an error handler in the controller

@ExceptionHandler
public @ResponseBody String handle(BadRequestException e) {
    return "I'm the body";
}

or user the global error handler if you're on 3.2 or above

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public @ResponseBody String handleBadRequestException(BadRequestException ex) {
        return "I'm the body";
    }
}

with this the body will be populate, you should populate it with your error message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!