0

I have a custom Exception class which I want to return as a json when an exception occurs.

SpringCacheException.java

@JsonSerialize
public class SpringCacheException extends Exception{
    private static final long serialVersionUID = 1L;
    private HttpStatus status;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
    private LocalDateTime timestamp;
    private String message;
    private String debugMessage;
    public SpringCacheException(HttpStatus status, String message, String debugMessage) {
        super();
        this.setStatus(status);
        this.message = message;
        this.debugMessage = debugMessage;
    }
    public SpringCacheException() {
        timestamp = LocalDateTime.now();
    }

    public SpringCacheException(HttpStatus status) {
        this();
        this.setStatus(status);
    }

    public SpringCacheException(HttpStatus status, Throwable ex) {
        this();
        this.setStatus(status);
        this.setMessage("Unexpected error");
        this.setDebugMessage(ex.getLocalizedMessage());
    }

    public SpringCacheException(HttpStatus status, String message, Throwable ex) {
        this();
        this.setStatus(status);
        this.setMessage(message);
        this.setDebugMessage(ex.getLocalizedMessage());
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getDebugMessage() {
        return debugMessage;
    }

    public void setDebugMessage(String debugMessage) {
        this.debugMessage = debugMessage;
    }
    public HttpStatus getStatus() {
        return status;
    }
    public void setStatus(HttpStatus status) {
        this.status = status;
    }
}

RestExceptionHandler.java

 @Order(Ordered.HIGHEST_PRECEDENCE)
    @ControllerAdvice
    public class RestExceptionHandler extends ResponseEntityExceptionHandler {
        private static final Logger logger= LoggerFactory.getLogger(ContactServiceImpl.class);

         @Override
            protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
                SpringCacheException errorMessage = new SpringCacheException(status.BAD_REQUEST,"My Error",ex);
                return new ResponseEntity<Object>(errorMessage, headers, status);
            }

@ExceptionHandler(SpringCacheException.class)
        ResponseEntity<Object> handleBadRequests(HttpStatus status,String message,SpringCacheException ex) throws IOException  {
            SpringCacheException errorMessage = new SpringCacheException(HttpStatus.BAD_REQUEST,"My Error",ex);
            return new ResponseEntity<Object>(errorMessage,HttpStatus.BAD_REQUEST);
        }
    }

Exception thrown:-

@Override
    public Contact show(int id) throws SpringCacheException  {
        try {
            Contact contact = contactRepository.findOneById(id);
            return contact;
        }
        catch (Exception e) {
            throw new SpringCacheException();
        }
    }

Here I am deleting the contact table from the DB and the exception is thrown and I am getting the below long response.

     Position: 111
2017-10-22 00:37:08.577  WARN 10336 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Failed to invoke @ExceptionHandler method: org.springframework.http.ResponseEntity<java.lang.Object> com.myapp.exception.RestExceptionHandler.handleBadRequests(org.springframework.http.HttpStatus,java.lang.String,com.myapp.exception.SpringCacheException) throws java.io.IOException

I just want a json of type SpringCacheException but I am getting this long json with incorrect data. Can any one tell me where I am doing wrong. Thanks !

The Entire code can be found at - https://github.com/iftekharkhan09/SpringCaching

2
  • I think you might have to convert your exception to something else to pass into the ResponseEntity constructor Commented Oct 21, 2017 at 19:27
  • @Jeff can you please tell me what changes i need to make ?? Commented Oct 21, 2017 at 20:01

1 Answer 1

1

Your exception handler method expects a single parameter of SpringCacheException object (The class in its annotation).

@ExceptionHandler(SpringCacheException.class)
        ResponseEntity<Object> handleBadRequests(SpringCacheException ex) throws IOException  {
            //SpringCacheException errorMessage = new SpringCacheException(HttpStatus.BAD_REQUEST,"My Error",ex);
            return new ResponseEntity<Object>(ex, HttpStatus.BAD_REQUEST);
        }
    }

By the way, creating a new SpringCacheException defeats the purpose of that handler. You are supposed to return the exception passed in to the method

I forked your project and fixed it here: https://github.com/olantobi/SpringCaching

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.