-1

I use this code to get Merchant name by ID.

@GetMapping("pages")
public Page<WpfPaymentsDTO> pages(@RequestParam(value = "page") int page, @RequestParam(value = "size") int size) {
    return wpfPaymentsService.findAll(page, size)
                             .map(g -> WpfPaymentsDTO.builder()
                             .id(g.getId())
                             .status(g.getStatus())
                             .merchant_id(getMerchantName(g.getMerchant_id()))
                             .build());  
}

private String getMerchantName(int id) {      
    Optional<Merchants> obj = merchantService.findById(id);       
    return obj.get().getName();
}

But when name is not found I get java.lang.NullPointerException: null at this line: .merchant_id(getMerchantName(g.getMerchant_id()))

Is there some way to set empty string and not to break the code when Object is not found?

Jens
  • 20,533
  • 11
  • 60
  • 86
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • 1
    Just add obj.ifPresent() check in getMerchantName method. If it is true use your code. Else return empty string. – Prasath Apr 01 '19 at 09:38
  • You can try including the code nested inside a "try, catch" expression, capturing the NullPointerException to prevent it from stopping the code – Pablo Alvarez Apr 01 '19 at 09:38
  • 1
    @PabloAlvarez No. https://stackoverflow.com/questions/18265940/when-is-it-ok-to-catch-nullpointerexception – m0skit0 Apr 01 '19 at 09:39

4 Answers4

2

Instead of calling obj.get().getName() use more optional-way solution like:

obj.map(Merchants::getName).orElse("");

which will return empty string when Merchants is not found. You can change "" in code above to any other default value which is more appropriate to your case.

If g.getMerchant_id() can be null code below will also handle this situation:

private String getMerchantName(Integer id) {      
    return Optional.ofNullable(id)
        .flatMap(i -> merchantService.findById(i))
        .map(Merchants::getName)
        .orElse(<default value>);
}

It will turn id into optional so when it will be null this code will just return <default value> otherwise it will use id to find Merchants and then get its name. flatMap is here to remove nested optionals.

Kamil Rafałko
  • 330
  • 2
  • 3
  • 15
1
private String getMerchantName(int id) {      
    Optional<Merchants> obj = merchantService.findById(id);    

    return obj.isPresent() ?  obj.get().getName() : "";
}
Prasath
  • 1,233
  • 2
  • 16
  • 38
1

You can return an empty string to avoid the NPE if the name is null :

private String getMerchantName(int id) {      
    Optional<Merchants> obj = merchantService.findById(id);       
    return obj.isPresent() ?  obj.get().getName() : "";
}

Then the method merchant_id should handle an empty string and perhaps throws an exception (IllegalArgumentException for example).

Andrianekena Moise
  • 1,018
  • 7
  • 16
0

I think we can determine if this object is empty before we return it