I have a REST service which could throw an exception.
This is my custom exception
public class CommentNotPostableException extends Exception {
public CommentNotPostableException(final String message) {
super(message);
}
}
Then, for my REST Api, I implemented a RestResponseEntityExceptionHandler
which extends ResponseEntityExceptionHandler
One of its methods is
@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());
}
which should get the exception...
Now my controller is (snippet)
public ResponseEntity<?> postComment(@Valid @RequestBody CommentDTO dto, Errors errors) throws CommentNotPostableException{
.....
if(service.hasAlreadyPosted(user, reservation)){
throw new CommentNotPostableException("Already posted");
}
....
}
So, when hitting the exception i should recevive an error 46, instead i'm getting a 500 error, even if my custom exception is taken into account... Is there some kind of ordering in exceptions?
{
"timestamp": 1496084392755,
"status": 500,
"error": "Internal Server Error",
"exception": "it.besmart.easyparking.exceptions.CommentNotPostableException",
"message": "Already posted",
"path": "/api/oauth/comment/new"
}
this is what i get from logs
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]