How to throw custom exception with custom values in Java?

Solution 1:

Lets make a custom ResourceAlreadyExistsException class . It will extends the RuntimeException class, and you can add as many parameters to it as you like. I've kept it concise like this.

public class ResourceAlreadyExistsException extends RuntimeException {

    public ResourceAlreadyExistsException(String property, String value) {
        super(String.format(
            "Resource with property %s and value %s already exists." +
            "Make sure to insert a unique value for %s",
            property, value, property));
    }
}

Whenever I need to check for a unique resource, I can tell the user which specific property has what value that causes the error. Furthermore, I notify the user what action must be taken to avoid the error.

Say, I chose to use error *** for my ResourceAlreadyExistsException. Still, I need to hook up this error message to the ExceptionResponseHandler. The extra method is very similar to the method that we usually create for handling all exceptions. In fact, you can easily copy-paste this method for all the exceptions you have. All you have to do, is changing the Exception class to your exception and change the HttpStatus..

@ExceptionHandler(ResourceAlreadyExistsException.class)
public final ResponseEntity<ExceptionResponse> handleResourceAlreadyExistsException(
    ResourceAlreadyExistsException ex, WebRequest req) {
    ExceptionResponse exceptionResponse = new ExceptionResponse(
        new Date(),
        ex.getMessage(),
        req.getDescription(false)
    );
    return new ResponseEntity<>(exceptionResponse, HttpStatus.UNPROCESSABLE_ENTITY);