【问题标题】:Sonarqube critical issue "Define and throw a dedicated exception instead of using a generic one"Sonarqube 关键问题“定义并抛出专用异常而不是使用通用异常”
【发布时间】:2021-10-07 11:27:49
【问题描述】:

您好,我有以下方法可以解决一个严重的声纳问题(定义并抛出一个专用异常,而不是使用通用异常)

当我删除“异常”并提及专用异常(IOException、SAXException、ParserConfigurationException)时。当时声纳提出了一个重大问题“使用通用的”。

public Element createDomElement(String xmlRequest) throws Exception {
        DocumentBuilder documentBuilder;
        Document document = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newDefaultInstance();
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        dbf.setNamespaceAware(true);
        documentBuilder = dbf.newDocumentBuilder();

        if (documentBuilder == null) {
            throw new ABCException(null, "unexpected_error", "Error processing request", null,
                    INTERNAL_SERVER_ERROR);
        }

        synchronized (this) {
            document = documentBuilder.parse(new ByteArrayInputStream(xmlRequest.getBytes(UTF_8)));
        }
        document.getDocumentElement().normalize();
        return document.getDocumentElement();
    }

不知道如何解决,请有人帮我解决这个问题。

【问题讨论】:

    标签: java java-11


    【解决方案1】:

    是因为抛出时缺少 ABCException 吗?请您尝试下面的方法签名并运行 sonarqube 吗?

    public Element createDomElement(String xmlRequest) throws ParserConfigurationException, ABCException, SAXException, IOException {}
    

    编辑 1
    解决此问题的方法

    1. 从 createDomElement() 方法中仅抛出 ABCException。在 createDomElement() 本身中处理剩余异常。不知道是不是推荐的。
    public Element createDomElement(String xmlRequest) throws ABCException {
            DocumentBuilder documentBuilder;
            Document document = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newDefaultInstance();
            try {
                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            } catch (ParserConfigurationException e) {
                throw new ABCException(null, "Parser Error", "Error processing request", null,
                        "Parser Error : " + e.getMessage());
            }
    //todo remaining part of method
    }
    
    1. 重构代码并划分 createDomElement() 方法以遵循单一职责。这种方法看起来比第一种更好。检查这个答案https://softwareengineering.stackexchange.com/a/264068

    【讨论】:

    • 仍然收到消息重构此方法以最多抛出一个检查异常,而不是:javax.xml.parsers.ParserConfigurationException、org.xml.sax.SAXException、java.io.IOException
    • 用可能的方法更新了我的答案
    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多