简体   繁体   中英

Exception Mapping in Restful Spring boot application

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM