Skip to content

Instantly share code, notes, and snippets.

@daniel-shuy
Last active February 7, 2020 03:56
Show Gist options
  • Save daniel-shuy/f79dc13cd839bd514d336d0c0557b2d1 to your computer and use it in GitHub Desktop.
Save daniel-shuy/f79dc13cd839bd514d336d0c0557b2d1 to your computer and use it in GitHub Desktop.
Spring MVC ResponseBodyAdvice to return HTTP 404 if Response Body is an empty Optional
@ControllerAdvice
public class EmptyOptionalResponseBodyControllerAdvice implements ResponseBodyAdvice<Optional<?>> {
@Override
public boolean supports(MethodParameter returnType, @Nullable Class<? extends HttpMessageConverter<?>> converterType) {
return Optional.class.isAssignableFrom(returnType.getParameterType());
}
@Override
public Optional<?> beforeBodyWrite(Optional<?> body, @Nullable MethodParameter returnType, @Nullable MediaType selectedContentType,
@Nullable Class<? extends HttpMessageConverter<?>> selectedConverterType,
@Nullable ServerHttpRequest request, @Nullable ServerHttpResponse response) {
if (body.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
return body;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment