Reputation: 221
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
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