Last active
February 7, 2020 03:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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