Adrian
Adrian

Reputation: 11

How to return server response with output body not null?

When I return an exception, i can't return also the body. Once I get an exception I have to return the output of my body and the error message. I want that output is not null.

{
    "output": null,
    "errorMessages": {
        "EXCEPTION": "Errors string"
    }
}

LIKE THIS (with output)

{
    "output": {
"a"="string",
"b"="string"
}
    "errorMessages": {
        "EXCEPTION": "Errors string"
    }
}

My handler

public abstract class class extends CommonHandler {
    
    @Autowired
    private Servic service;



    protected Mono<ServerResponse> handleRequest(ServerRequest request) {
    return this.handleLock(request).flatMap(element -> ServerResponse.ok().bodyValue(new 
         RestResponse<>(element)))
            .onErrorResume(MyException.class, this::onConflictException);
//  .onErrorResume(Throwable.class, this::onGenericError);
    }



    private Mono<Object> handle(ServerRequest request) {
    String pathParam = request.pathVariable("pathParam");
    Long id = Long.parseLong(request.pathVariable("id"));
    return request.bodyToMono(Object.class).flatMap(body -> service.s(body, pathParam, id));
    }
    }

My common Handler

import reactor.core.publisher.Mono;

public abstract class CommonHandler  {

    
    protected Mono<ServerResponse> onConflictException(MyException e) {
        return Mono.just(e.getMessage()).flatMap(s -> 
    ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .bodyValue(new RestResponse<>(ErrorCode.INTERNAL_SERVER_ERROR.getValue(), 
s)));
    }
    
    protected Mono<ServerResponse> onGenericError(Throwable e) {
        return Mono.just(e.getMessage()).flatMap(s -> 
     ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .bodyValue(new RestResponse<>(ErrorCode.INTERNAL_SERVER_ERROR.getValue(), 
  s)));
    }

}    

Thank's for help.

Upvotes: 1

Views: 274

Answers (0)

Related Questions