![](/img/trans.png)
[英]Correct way to log exceptions using log4j and Solarlint compliant
[英]Correct use of log4j and Exceptions
我對將Log4j與Exceptions配合使用有疑問。 我想將消息記錄到我的日志文件中,但我不知道如何處理異常。 我只需要使用例外(因為已經在我的日志文件中打印了)或一些其他東西:
try {
Configurations.getInstance().getProperty("DynamoDBProfileCredentials");
credentials = new ProfileCredentialsProvider( Configurations.getInstance().getProperty("DynamoDBProfileCredentials")).getCredentials();
} catch (Exception e) {
log.error(new AmazonClientException("Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.",e));
或這個
try {
Configurations.getInstance().getProperty("DynamoDBProfileCredentials");
credentials = new ProfileCredentialsProvider( Configurations.getInstance().getProperty("DynamoDBProfileCredentials")).getCredentials();
} catch (Exception e) {
log.error("Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.",e);
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.",
e);
提前致謝。
異常只是信號/事件; 在您的應用程序范圍內發生。 記錄這些是另一個主題。
我了解您需要在應用程序中記錄有用的消息。 在您的情況下,您可以在方法的使用者上觸發日志事件,也可以直接在執行時觸發日志事件。
最簡單的情況是:
try {
Configurations.getInstance().getProperty("DynamoDBProfileCredentials");
credentials = new ProfileCredentialsProvider( Configurations.getInstance().getProperty("DynamoDBProfileCredentials")).getCredentials();
} catch (Exception e) {
AmazonClientException ace = AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.", e);
log.error(ace.getMessage(), ace);
throw ace;
}
要么
try {
Configurations.getInstance().getProperty("DynamoDBProfileCredentials");
credentials = new ProfileCredentialsProvider( Configurations.getInstance().getProperty("DynamoDBProfileCredentials")).getCredentials();
} catch (Exception e) {
log.error("Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (C:\\Users\\your username\\credentials), and is in valid format.",e);
throw new AmazonClientException(e);
}
上面的示例只是一個實現,而不是原始問題的答案。 要回答原始問題,您必須對API以及API設計產生的職責有清晰的了解。 您是否要在您的API中進行登錄還是要向調用方發出發生異常的信號? 還是兩者都一樣(就像上面的示例一樣?)。
在使用異常或任何其他方式傳播意外狀態之前,請先回答以下問題:應如何處理這種情況? 發生異常后應該怎么辦? 日志記錄也不例外。 它只是記錄。 找到答案后,您可以尋找適當的方式傳達意外狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.