Spring启动+ REST异常处理程序 - 总是得到500错误

时间:2017-05-29 19:11:33

标签: spring rest

我有一个可以抛出异常的REST服务。

这是我的自定义异常

public class CommentNotPostableException extends Exception {

        public CommentNotPostableException(final String message) {
            super(message);
        }

    }

然后,对于我的REST Api,我实现了RestResponseEntityExceptionHandler扩展ResponseEntityExceptionHandler 其中一种方法是

@ExceptionHandler(value = { CommentNotPostableException.class })
    protected ResponseEntity<Object> handleCommentNotPostableException(CommentNotPostableException ex, WebRequest request) {
        StringBuilder builder = new StringBuilder();
        builder.append(ex.getMessage());

        ApiError apiError = new ApiError(HttpStatus.valueOf(46), 
          ex.getLocalizedMessage(), builder.substring(0, builder.length()));
        logger.error("Already posted", ex);
       return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
     }

应该得到例外......

现在我的控制器是(摘录)

public ResponseEntity<?> postComment(@Valid @RequestBody CommentDTO dto, Errors errors) throws CommentNotPostableException{
.....

    if(service.hasAlreadyPosted(user, reservation)){
                throw new CommentNotPostableException("Already posted");
            }

....
}

所以,当遇到异常时我应该接收到错误46,而不是我得到500错误,即使考虑到我的自定义异常......在例外中是否有某种排序?

{
  "timestamp": 1496084392755,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "it.besmart.easyparking.exceptions.CommentNotPostableException",
  "message": "Already posted",
  "path": "/api/oauth/comment/new"
}

这是我从日志中得到的

2017-05-29 21:13:32 DEBUG i.b.e.w.r.CommentRestController[57] - dto è CommentDTO [comment=A, vote=3, reservationId=7161]
2017-05-29 21:13:32 ERROR o.a.c.c.C.[.[.[.[dispatcherServlet][181] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is it.besmart.easyparking.exceptions.CommentNotPostableException: Already posted] with root cause
it.besmart.easyparking.exceptions.CommentNotPostableException: Already posted
    at it.besmart.easyparking.web.restcontroller.CommentRestController.postComment(CommentRestController.java:78) ~[classes/:na]

0 个答案:

没有答案