user630209
user630209

Reputation: 1207

How can we give different customs messages for the same exception

Since handling this scenario for the first time, asking to know which is best approach.

Here for all the DataIntegrityViolationException, sending the same error message

@Override
public boolean saveParam(ParamDto dto) throws ParamException 
{
    try 
    {
        return super.save(dto);
    }
    catch(DataIntegrityViolationException e)
    {
        throw new ParamException(ParamException.INTERNAL_SERVER_ERROR, messageSource.getMessage(CodeEnum.DUPLICATE_APP.getValue(), new Object[] { dto.getParamKey() }, Locale.ENGLISH));
    } 
    catch (GenericException ge) 
    {
        throw new ParamException(ge, ge.getRootCauseMessage());
    }
}

How can we give different customs messages for the same exception. Do we need to check the message string ?

Here having 2 different kind of exception under DataIntegrityViolationException.

  1. "ERROR: value too long for type character(1)" (id=172) ""

  2. "ERROR: duplicate key value violates unique constraint "uk_param_key"\n Detail: Key (param_key)=(Test1) already exists."

Upvotes: 0

Views: 409

Answers (1)

Bunti
Bunti

Reputation: 1760

As you're already doing once you have caught the DataIntegrityViolationException exception use getMostSpecificCause method to get the actual cause of the exception.

Then you can check to see if the exception is of specific type with instanceof keyword and customize your message accordingly. For example, MySQL JDBC driver throws MysqlDataTruncation, MySQLIntegrityConstraintViolationException etc. for different types of errors. Check documentation to see the different types of exceptions thrown by your database driver.

Also you can check the exception message and compare it with a pre-defined message but this is a bit tricky and error-prone.

Upvotes: 1

Related Questions