Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging in Java 8 Optional

I have some code where I'm using Java 8 Optional in which I want to log an error when I don't get the required result.

As shown in following Example I have commented on a line where I get the error when I'm trying to log Error Message:

    @PutMapping("/organs/{id}")
    public Organ updateorgan(@PathVariable(value = "id") Long organId,
                                           @Valid @RequestBody Organ organDetails) {

        Organ organ = organRepository.findById(organId)
                .orElseThrow(() -> 
                   // LOG.log(Level.SEVERE,"Organ with id "+organId + "not found");
                   new ResourceNotFoundException("organ", "id", organId)
                );

        organ.setName(organDetails.getName());
        Organ updatedOrgan = organRepository.save(organ);
        LOG.info("Updated organ details. Response :"+updatedOrgan);
        return updatedOrgan;
    }

P.S - I only want to use the Java 8 method and not conventional approach.

Thanks in advance!

like image 511
I'm_Pratik Avatar asked Nov 19 '19 09:11

I'm_Pratik


People also ask

What is the use of optional in java 8?

Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.

How do I return optional in java 8?

Optional is a container object which may or may not contain a non-null value. You must import java. util package to use this class. If a value is present, isPresent() will return true and get() will return the value.

Which are the valid way of creating optional instance?

The are three creational methods for creating an optional instance. Returns an empty Optional instance. Optional<String> empty = Optional. empty();


2 Answers

Make it a lambda with a body enclosed by curly braces and a return statement instead of an expression lambda:

Organ organ = organRepository.findById(organId)
                .orElseThrow(() -> {
                    LOG.log(Level.SEVERE,"Organ with id "+organId + "not found");
                    return new ResourceNotFoundException("organ", "id", organId);
                });
like image 149
Jesper Avatar answered Sep 18 '22 06:09

Jesper


You have to use return

Organ organ = organRepository.findById(organId)
        .orElseThrow(() -> {
            LOG.log(Level.SEVERE,"Organ with id "+organId + "not found");
            return new ResourceNotFoundException("organ", "id", organId);
        });
like image 23
YCF_L Avatar answered Sep 20 '22 06:09

YCF_L