Joy
Joy

Reputation: 4473

Issue in returning error message and description from rest controller in Spring

I have written following controller :

 @RestController
 @GetMapping(value = "/api", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
 public ResponseEntity<?> getListOfPOWithItem(@QueryParam("input1") String input1,
                                        @QueryParam("input2") String input2)
                                   throws  EntityNotFoundException {

   List<Output> oList = myService.getOutput(input1, input2);
   if (oList != null) {
       return new ResponseEntity<List<Output>>(oList, HttpStatus.OK);
    }
}

And associated exception handler as follows:

@RestControllerAdvice
@ApiIgnore
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(EntityNotFoundException.class)
public final ResponseEntity<ExceptionResponse> handleEntityNotFoundException(EntityNotFoundException ex,
  WebRequest request) {

  log(ex);

  ExceptionResponse exceptionResponse = new ExceptionResponse(Instant.now().toEpochMilli(),
    ex.getMessage(), request.getDescription(true));

  return new ResponseEntity<>(exceptionResponse, HttpStatus.NO_CONTENT);
}

And ExcetionResponse is as follows:

public class  ExceptionResponse {
 private long timestamp;
 private String message;
 private String details;

 public ExceptionResponse(long timestamp, String message, String details) 
{
 super();
 this.timestamp = timestamp;
 this.message = message;
 this.details = details;
}

public long getTimestamp() {
 return timestamp;
}

public String getMessage() {
 return message;
}

public String getDetails() {
 return details;
}

}

Even after that, in case of EntityNotFoundException, I am getting only 204 in response, no error message or description. I want error response as follows:

  {
     message : 
     {
                 timestamp:<>,
                 message:<>,
                 details:<>   
      }
  }

I have taken help from this post: Not able to return error code with message from rest API in Spring boot, but cannot fix this. Can anyone please help me figuring out what I am missing here ? Thanks.

Upvotes: 1

Views: 456

Answers (2)

DevApp
DevApp

Reputation: 83

    @ControllerAdvice
public class ExceptionHandle {
    @ExceptionHandler({ InvalidDataInputException.class, RelationNotFoundException.class,
            ActionIsInvalidException.class })
    public final ResponseEntity<ErrorMessage> handleSpecificExceptions(Exception ex, WebRequest request) {
        ErrorMessage errorMessage = new ErrorMessage(new Date(), ex.getMessage(), request.getDescription(false));
        return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

This is my Global exceptional handler.

   @Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ErrorMessage {
    private Date timestamp;
    private String message;
    private String details;

}

This is ErrorMessage.(I am using Date for timestamp)

   public class InvalidDataInputException extends RuntimeException {
    public InvalidDataInputException(String message) {
        super(message);
    }
}

This is one exception am throwing.

if (retEmployee == null) {
            throw new InvalidDataInputException("Invalid data input");
        }

Hope this helps:)

Upvotes: 0

AKSHAY SACHAN
AKSHAY SACHAN

Reputation: 1

Why are you extending ResponseEntityExceptionHandler? @RestControllerAdvice will work with all the classes annotated with @RestController. Just make sure that both the RestController and RestControllerAdvice annotated classes are in the package that are scanned by SPRING.

Also if you do want to extend the ResponseEntityExceptionHandler following doc might help you:

Note that in order for an @ControllerAdvice subclass to be detected, ExceptionHandlerExceptionResolver must be configured

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.html

Upvotes: 0

Related Questions