Restful Spring启动应用程序中的异常映射

时间:2017-10-21 19:15:37

标签: java spring-boot exception-handling exceptionmapper

我有一个自定义的Exception类,我想在发生异常时将其作为json返回。

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);
        }
    }

抛出异常: -

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

这里我将从数据库中删除联系人表,并抛出异常,我收到以下长时间的响应。

     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

我只想要一个类型为SpringCacheException的json,但是我得到的这个长json的数据不正确。任何人都可以告诉我我做错了什么。谢谢!

可以在 - https://github.com/iftekharkhan09/SpringCaching

找到整个代码

1 个答案:

答案 0 :(得分:1)

您的异常处理程序方法需要SpringCacheException对象的单个参数(其注释中的类)。

@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);
        }
    }

顺便说一句,创建一个新的SpringCacheException会破坏该处理程序的目的。您应该返回传递给方法

的异常

我将您的项目分叉并在此处修复:https://github.com/olantobi/SpringCaching