'Custom exception thrown from enum is not caught in @ExceptionalHandler
Question: How to catch the custom exception in @ExceptionalHandler method.
I have a request body in the controller which takes a enum value. I have written a enum
public enum Car{
TOYOTA;
@JsonCreator
public static Car fromValue(String value) throws Exception{
if(value !=null){
for(Car enumvalue: Car.class.getEnumConstants()){
if(enumValue.name().toLowerCase().equals(value.toLowerCase())){
return enumValue;
}
}
}
throw new MyCustomException("Incorrect enum value");
}
}
Below is the exceptional handler method i have written in controller
@ExceptionHandler(MyCustomException.class)
public ResponseEntity<Object> handleEnum(MyCustomException e){
//code to send the response back with custom message
}
Exceptional Handler method works if I handle ValueInstantiationException instead of MyCustomException
Logs:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of com.demo.model.Domain, problem: Incorrect enum Value; nested exception is com.fasterxml.jackson.databind.exc.ValueInstantiationException:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
