Alexey Tykhonov
Alexey Tykhonov

Reputation: 11

Managing NullPointer Exception in SpringBoot Web-flux

My code calls for Mono element from Flux base of elements (already created). Includes @Repository class with "getJobById" and @Component class "Handler" to process request like getAll, getJobById, post, put, delete. If I input wrong id - can't handle exception and receive NullPointerException error. I want to catch the exception instead.

Error:

java.lang.NullPointerException: null at com.javasampleapproach.webflux.repo.impl.JobClientRepositoryImpl.getJobById(JobClientRepositoryImpl.java:32) ~[classes/:na]
    at com.javasampleapproach.webflux.functional.handler.JobClientHandler.getJobById(JobClientHandler.java:52) ~[classes/:na]

Already tried this:

@ControllerAdvice
public class ClientExceptionController  {
@ExceptionHandler(value = ClientNotfoundException.class)
public ResponseEntity<Object> exception(ClientNotfoundException exception) {return new ResponseEntity<>("Id not found", HttpStatus.NOT_FOUND);}

+

public class ClientNotfoundException extends NullPointerException{
    public ClientNotfoundException() {}
    public ClientNotfoundException(String s) {
        super(s);
    }

and in Handler and Repository classes:

if(jobClientRepository.getJobById(jobId).equals(null)) throw new ClientNotfoundException();

Also I tried like:

 Mono<JobClient> jobMono = jobClientRepository.getJobById(jobId)
.onErrorResume(e->Mono.empty());
 @Component
    public Mono<ServerResponse> getJobById(ServerRequest request) {
            long jobId = Long.valueOf(request.pathVariable("id"));
            Mono<ServerResponse> notFound = ServerResponse.notFound().build();

And I tried this:

  if(jobClientRepository.getJobById(jobId).equals(null)) throw new ClientNotfoundException();

Error appears here:

Mono<JobClient> jobMono = jobClientRepository.getJobById(jobId).onErrorResume(e->Mono.empty());
return jobMono.flatMap(job -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(fromObject(job))).switchIfEmpty(notFound).onErrorResume(ClientNotfoundException.class, e -> notFound);

@Repository 
@Override
public Mono<JobClient> getJobById(Long id)  {if(jobStores.get(id).equals(null)) throw new ClientNotfoundException();
return Mono.just(jobStores.get(id)).onErrorResume(e -> Mono.error(new ClientNotfoundException("Correct ID is required"+e)));

Upvotes: 1

Views: 6570

Answers (2)

Toerktumlare
Toerktumlare

Reputation: 14810

You need to separate regular programming from reactive programming. Try this.

@Repository 
@Override
public Mono<JobClient> getJobById(Long id)  {
    return Optional.ofNullable(jobStore.get(id))
            .map(Mono::just)
            .orElseGet(Mono::empty);
}

//Then call it
getJobById(1L).map(jobClient -> ServerResponse.ok()
            .contentType(MediaType.APPLICATION_JSON)
            .syncBody(jobClient)
        ).switchIfEmpty(Mono.error(ClientNotfoundException::new));

Havnt run the code wrote it on mobile.

Upvotes: 1

sagarr
sagarr

Reputation: 1212

Try this:

@Repository 
@Override
public Mono<JobClient> getJobById(Long id)  {
    if(jobStores.get(id) == null) throw new ClientNotfoundException();
    return Mono.just(jobStores.get(id)).onErrorResume(e -> Mono.error(new ClientNotfoundException("Correct ID is required"+e)));
}

In java you avoid NullPointerException by first checking whether given object is null or not and then proceed with calling its method like

if (obj != null) {
    obj.doSomething();
}

Upvotes: 0

Related Questions