2

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]
MarioC
  • 2,934
  • 15
  • 59
  • 111
  • I always use @ControllerAdvice for that and it works flawlessly. See: http://www.journaldev.com/2651/spring-mvc-exception-handling-controlleradvice-exceptionhandler-handlerexceptionresolver for examples. They should do the trick for you. – Rafal G. May 29 '17 at 19:22
  • that's how i'm working, my ExceptionHandler class is annotated with ControllerAdvice, and every Exception with ExceptionHandler – MarioC May 29 '17 at 19:35
  • 2
    okay. I think you want to override `valueOf(param1)` method in `HttpStatus` enum here. The reason why it is always returning 500 is because `46` is not a valid Http Response in `HttpStatus` enum and valueOf() method is doing this. `public static HttpStatus valueOf(int statusCode) { for (HttpStatus status : values()) { if (status.value == statusCode) { return status; } } throw new IllegalArgumentException("No matching constant for [" + statusCode + "]"); }` – harshavmb May 30 '17 at 07:08
  • You can follow https://stackoverflow.com/questions/7662424/how-do-i-reimplement-valueof-on-enumeration to create a custom enum returning 46 status code. – harshavmb May 30 '17 at 07:10
  • 1
    Thanks, the problem was really my custom response codes! – MarioC May 30 '17 at 21:36

0 Answers0