Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a way to customize what happens when Optional is empty #24

Closed
dinhani opened this issue Apr 8, 2017 · 2 comments
Closed

Add a way to customize what happens when Optional is empty #24

dinhani opened this issue Apr 8, 2017 · 2 comments

Comments

@dinhani
Copy link

dinhani commented Apr 8, 2017

I have this simple use case using Spring Boot serializing a java.util.Optional.

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Optional<User> getUser(@PathVariable("id") String id) {
    return queryUser.execute(id);        
}

It works fine when there is a value, but when the value is empty, it serializes it to null. I'd like to have a way to customize what happens when the value is empty, maybe passing a callback when creating the Jdk8Module instance.

For my current use case, I 'd like to throw an exception that represents a 404 error, but maybe in other applications it would be necessary to use another object instance representing the missing data.

@cowtowncoder
Copy link
Member

I guess the first thing would be to understand why you think alternate handling is needed: why doesn't method itsel fail if you want to throw an exception? What is the problem in serializing it as null that you are trying to solve?
Or if you do not want to serialize such value at all, JsonInclude.NON_ABSENT (or just NON_EMPTY which cover case of absent) can be used to configure behavior.

Beyond this it could perhaps be possible to allow alternate configuration of default Optional serializer this module provides, and then allowing passing differently configured instance.
But I want to first understand the problem to solve, before considering solutions.

@dinhani
Copy link
Author

dinhani commented Apr 12, 2017

You are right.

Actually I changed my code to this and dropped the Optional.

return queryUser.execute(id).orElseThrow(HttpStatusException.notFound());

My intention was not only for this use case, but also for other use cases where the developer might want to return something else, like a default value or dummy object instead of null.

But after thinking more deeply, I think all these use cases can be handled by the application code with custom getters when serializing the object and should not be responsibility of the library.

@dinhani dinhani closed this as completed Apr 12, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants