springspring-bootspring-annotationsspring-aspects

Spring Exception Handling (getting reason from message resource)


How can set reason from message.properties in @ResponseStatus?

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "**i want to get this from message resource**")
public class CreateOrderException extends RuntimeException{}

Solution

  • Consider using ExceptionHandlerAdvice instead of annotating the exception class. You can then intercept your CreateOrderException and shape your response according your needs.

    a code snippet would be:

    @ControllerAdvice
    public class ExceptionHandlerAdvice {
        @ExceptionHandler(CreateOrderException.class)
        public void handleException(CreateOrderException exception, HttpServlerResponse response){
             String msg = gettingMessageFromYourException(exception);
             response.sendError(400, msg);
        }
    }
    

    Don't forget to set your project parameter to send the message with error response: server.error.include-message by default it is hidden.

    Alternatively you may change return type of handleException to ResponseEntity and then build it according needs:

    ....
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(yourCustomResponseBody);