繁体   English   中英

我们如何针对同一例外情况提供不同的海关消息

[英]How can we give different customs messages for the same exception

自从第一次处理此方案以来,要求了解哪种方法最好。

在这里,对于所有DataIntegrityViolationException ,发送相同的错误消息

@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());
    }
}

对于相同的例外情况,我们如何提供不同的海关消息。 我们需要检查消息字符串吗?

这里在DataIntegrityViolationException下有2种不同的异常。

  1. “错误:类型字符(1)的值太长”(id = 172)“”

  2. “错误:重复的键值违反了唯一约束“ uk_param_key” \\ n详细信息:键(param_key)=(Test1)已存在。”

捕获DataIntegrityViolationException异常后,就像已经在做的DataIntegrityViolationException使用getMostSpecificCause方法获取异常的实际原因。

然后,您可以使用instanceof关键字检查异常是否为特定类型,并相应地自定义消息。 例如,MySQL JDBC驱动程序会针对不同类型的错误引发MysqlDataTruncationMySQLIntegrityConstraintViolationException等。 检查文档以查看数据库驱动程序引发的不同类型的异常。

您也可以检查异常消息并将其与预定义消息进行比较,但这有点棘手且容易出错。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM