solecoder
solecoder

Reputation: 221

How to use multiple error specific parameter in custom Exception constructor parameters?

I am building a custom exception something like this.

public class ValidationException extends RuntimeException {

    public validationException(String errorId, String errorMsg) {
        super(errorId, errorMsg);
    }
}

This of course throws error because RuntimeException doesn't have any such constructor to handle this.

I also want to fetch the errorId and errorMsg in my GlobalExceptionalHandler by

ex.getMessage();

But I want functions to fetch both the errorId and errorMessage separately. How can this be achieved ?

Upvotes: 0

Views: 1905

Answers (1)

Andrei Sfat
Andrei Sfat

Reputation: 8626

You want to the errorId and errorMsg as fields of ValidationException class, just like you would do with a normal class.

public class ValidationException extends RuntimeException {

    private String errorId;
    private String errorMsg;

    public validationException(String errorId, String errorMsg) {
        this.errorId = errorId;
        this.errorMsg = errorMsg;
    }

    public String getErrorId() {
        return this.errorId;
    }

    public String getErrorMsg() {
        return this.errorMsg;
    }
}

and in your GlobalExceptionHandler:

    @ExceptionHandler(ValidationException.class)
    public ResponseEntity<SomeObject> handleValidationException(ValidationException ex) {
        // here you can do whatever you like 
        ex.getErrorId(); 
        ex.getErrorMsg();
    }

Upvotes: 1

Related Questions