[EG-438] Error Reporting Framework (#6125)

* [EG-438] First commit of error code interface

* [EG-438] Implement error reporter and a few error codes

* [EG-438] Add unit tests and default properties files

* [EG-438] Add the error table builder

* [EG-438] Update initial properties files

* [EG-438] Add some Irish tests and the build.gradle

* [EG-438] Fall back for aliases and use different resource strategy

* [EG-438] Define the URL using a project-specific context

* [EG-438] Tidy up initialization code

* [EG-438] Add testing to generator and tidy up

* [EG-438] Remove direct dependency on core and add own logging config

* [EG-438] Fix compiler warnings and tidy up logging

* [EG-438] Fix detekt warnings

* [EG-438] Improve error messages

* [EG-438] Address first set of review comments

* [EG-438] Use enums and a builder for the reporter

* [EG-438] Add kdocs for error resource static methods

* [EG-438] Handle enums defined with underscores

* [EG-438] Slight refactoring of startup code

* [EG-438] Port changes to error reporting code from future branch

* [EG-438] Also port test changes

* [EG-438] Suppress a deliberately unused parameter
This commit is contained in:
James Higgs
2020-04-28 14:07:50 +01:00
committed by GitHub
parent 3b335ebb00
commit ab43238420
52 changed files with 869 additions and 5 deletions

View File

@ -0,0 +1,31 @@
package net.corda.common.logging.errorReporting
import net.corda.common.logging.CordaVersion
import java.util.*
/**
* Provides information specific to Corda to the error reporting library.
*
* The primary use of this is to provide the URL to the docs site where the error information is hosted.
*/
class CordaErrorContextProvider : ErrorContextProvider {
companion object {
private const val BASE_URL = "https://docs.corda.net/docs"
private const val OS_PAGES = "corda-os"
private const val ENTERPRISE_PAGES = "corda-enterprise"
private const val ERROR_CODE_PAGE = "error-codes.html"
}
override fun getURL(locale: Locale): String {
val versionNumber = CordaVersion.releaseVersion
// This slightly strange block here allows the code to be merged across to Enterprise with no changes.
val productVersion = if (CordaVersion.platformEditionCode == "OS") {
OS_PAGES
} else {
ENTERPRISE_PAGES
}
return "$BASE_URL/$productVersion/$versionNumber/$ERROR_CODE_PAGE"
}
}

View File

@ -0,0 +1,28 @@
package net.corda.common.logging.errorReporting
/**
* A type representing an error condition.
*
* Error codes should be used in situations where an error is expected and information can be provided back to the user about what they've
* done wrong. Each error code should have a resource bundle defined for it, which contains set of properties that define the error string
* in different languages. See the resource bundles in common/logging/src/main/resources/errorReporting for more details.
*/
interface ErrorCode<CODES> where CODES: ErrorCodes, CODES: Enum<CODES> {
/**
* The error code.
*
* Error codes are used to indicate what sort of error occurred. A unique code should be returned for each possible
* error condition that could be reported within the defined namespace. The code should very briefly describe what has gone wrong, e.g.
* "failed-to-store" or "connection-unavailable".
*/
val code: CODES
/**
* Parameters to pass to the string template when reporting this error. The corresponding template that defines the error string in the
* resource bundle must be expecting this list of parameters. Parameters should be in the order required by the message template - for
* example, if the message template is "This error has argument {0} and argument {1}", the first element of this list will be placed
* into {0}.
*/
val parameters: List<Any>
}

View File

@ -0,0 +1,16 @@
package net.corda.common.logging.errorReporting
/**
* A collection of error codes.
*
* Types implementing this are required to be enum classes to be used in an error.
*/
interface ErrorCodes {
/**
* The namespace of this collection of errors.
*
* These are used to partition errors into categories, e.g. "database" or "cordapp". Namespaces should be unique, which can be enforced
* by using enum elements.
*/
val namespace: String
}

View File

@ -0,0 +1,24 @@
package net.corda.common.logging.errorReporting
import java.util.*
/**
* Provide context around reported errors by supplying product specific information.
*/
interface ErrorContextProvider {
/**
* Get the URL to the docs site where the error codes are hosted.
*
* Note that the correct docs site link is likely to depend on the following:
* - The locale of the error message
* - The product the error was reported from
* - The version of the product the error was reported from
*
* The returned URL must be the link the to the error code table in the documentation.
*
* @param locale The locale of the link
* @return The URL of the docs site, to be printed in the logs
*/
fun getURL(locale: Locale) : String
}

View File

@ -0,0 +1,16 @@
package net.corda.common.logging.errorReporting
import org.slf4j.Logger
/**
* Reports error conditions to the logs, using localised error messages.
*/
internal interface ErrorReporter {
/**
* Report a particular error condition
*
* @param error The error to report
* @param logger The logger to use when reporting this error
*/
fun report(error: ErrorCode<*>, logger: Logger)
}

View File

@ -0,0 +1,36 @@
package net.corda.common.logging.errorReporting
import org.slf4j.Logger
import java.text.MessageFormat
import java.util.*
internal const val ERROR_INFO_RESOURCE = "ErrorInfo"
internal const val ERROR_CODE_MESSAGE = "errorCodeMessage"
internal const val ERROR_CODE_URL = "errorCodeUrl"
internal class ErrorReporterImpl(private val resourceLocation: String,
private val locale: Locale,
private val errorContextProvider: ErrorContextProvider) : ErrorReporter {
private fun fetchAndFormat(resource: String, property: String, params: Array<out Any>) : String {
val bundle = ResourceBundle.getBundle(resource, locale)
val template = bundle.getString(property)
val formatter = MessageFormat(template, locale)
return formatter.format(params)
}
// Returns the string appended to all reported errors, indicating the error code and the URL to go to.
// e.g. [Code: my-error-code, For further information, please go to https://docs.corda.net/corda-os/4.5/error-codes.html]
private fun getErrorInfo(error: ErrorCode<*>) : String {
val resource = "$resourceLocation/$ERROR_INFO_RESOURCE"
val codeMessage = fetchAndFormat(resource, ERROR_CODE_MESSAGE, arrayOf(error.formatCode()))
val urlMessage = fetchAndFormat(resource, ERROR_CODE_URL, arrayOf(errorContextProvider.getURL(locale)))
return "[$codeMessage, $urlMessage]"
}
override fun report(error: ErrorCode<*>, logger: Logger) {
val errorResource = ErrorResource.fromErrorCode(error, resourceLocation, locale)
val message = "${errorResource.getErrorMessage(error.parameters.toTypedArray())} ${getErrorInfo(error)}"
logger.error(message)
}
}

View File

@ -0,0 +1,66 @@
package net.corda.common.logging.errorReporting
import java.lang.UnsupportedOperationException
import java.util.*
/**
* Entry point into the Error Reporting framework.
*
* This creates the error reporter used to report errors. The `initialiseReporting` method should be called to build a reporter before any
* errors are reported.
*/
class ErrorReporting private constructor(private val localeString: String,
private val resourceLocation: String,
private val contextProvider: ErrorContextProvider?) {
constructor() : this(DEFAULT_LOCALE, DEFAULT_LOCATION, null)
private companion object {
private const val DEFAULT_LOCALE = "en-US"
private const val DEFAULT_LOCATION = "."
private var errorReporter: ErrorReporter? = null
}
/**
* Set the locale to use when reporting errors
*
* @param locale The locale tag to use when reporting errors, e.g. en-US
*/
@Suppress("UNUSED_PARAMETER")
fun withLocale(locale: String) : ErrorReporting {
// Currently, if anything other than the default is used this is entirely untested. As a result, an exception is thrown here to
// indicate that this functionality is not ready at this point in time.
throw LocaleSettingUnsupportedException()
}
/**
* Set the location of the resource bundles containing the error codes.
*
* @param location The location within the JAR of the resource bundle
*/
fun usingResourcesAt(location: String) : ErrorReporting {
return ErrorReporting(localeString, location, contextProvider)
}
fun withContextProvider(contextProvider: ErrorContextProvider) : ErrorReporting {
return ErrorReporting(localeString, resourceLocation, contextProvider)
}
/**
* Set up the reporting of errors.
*/
fun initialiseReporting() {
if (contextProvider == null) {
throw NoContextProviderSuppliedException()
}
if (errorReporter != null) {
throw DoubleInitializationException()
}
errorReporter = ErrorReporterImpl(resourceLocation, Locale.forLanguageTag(localeString), contextProvider)
}
internal fun getReporter() : ErrorReporter {
return errorReporter ?: throw ReportingUninitializedException()
}
}

View File

@ -0,0 +1,27 @@
package net.corda.common.logging.errorReporting
abstract class ErrorReportingException(message: String, cause: Throwable? = null) : Exception(message, cause)
/**
* Occurs when reporting is requested before the error reporting code has been initialized
*/
class ReportingUninitializedException : ErrorReportingException("Error reporting is uninitialized")
/**
* Occurs when no error context provider is supplied while initializing error reporting
*/
class NoContextProviderSuppliedException
: ErrorReportingException("No error context provider was supplied when initializing error reporting")
/**
* Occurs if the error reporting framework has been initialized twice
*/
class DoubleInitializationException : ErrorReportingException("Error reporting has previously been initialized")
/**
* Occurs if a locale is set while initializing the error reporting framework.
*
* This is done as locale support has not yet been properly designed, and so using anything other than the default is untested.
*/
class LocaleSettingUnsupportedException :
ErrorReportingException("Setting a locale other than the default is not supported in the first release")

View File

@ -0,0 +1,18 @@
package net.corda.common.logging.errorReporting
import org.slf4j.Logger
/**
* Report errors that have occurred.
*
* Doing this allows the error reporting framework to find the corresponding resources for the error and pick the correct locale.
*
* @param error The error that has occurred.
*/
fun Logger.report(error: ErrorCode<*>) = ErrorReporting().getReporter().report(error, this)
internal fun ErrorCode<*>.formatCode() : String {
val namespaceString = this.code.namespace.toLowerCase().replace("_", "-")
val codeString = this.code.toString().toLowerCase().replace("_", "-")
return "$namespaceString-$codeString"
}

View File

@ -0,0 +1,60 @@
package net.corda.common.logging.errorReporting
import net.corda.common.logging.errorReporting.ResourceBundleProperties.ACTIONS_TO_FIX
import net.corda.common.logging.errorReporting.ResourceBundleProperties.ALIASES
import net.corda.common.logging.errorReporting.ResourceBundleProperties.MESSAGE_TEMPLATE
import net.corda.common.logging.errorReporting.ResourceBundleProperties.SHORT_DESCRIPTION
import java.text.MessageFormat
import java.util.*
/**
* A representation of a single error resource file.
*
* This handles selecting the right properties from the resource bundle and formatting the error message.
*/
class ErrorResource private constructor(private val bundle: ResourceBundle,
private val locale: Locale) {
companion object {
/**
* Construct an error resource from a provided code.
*
* @param errorCode The code to get the resource bundle for
* @param resourceLocation The location in the JAR of the error code resource bundles
* @param locale The locale to use for this resource
*/
fun fromErrorCode(errorCode: ErrorCode<*>, resourceLocation: String, locale: Locale) : ErrorResource {
val resource = "$resourceLocation/${errorCode.formatCode()}"
val bundle = ResourceBundle.getBundle(resource, locale)
return ErrorResource(bundle, locale)
}
/**
* Construct an error resource using resources loaded in a given classloader
*
* @param resource The resource bundle to load
* @param classLoader The classloader used to load the resource bundles
* @param locale The locale to use for this resource
*/
fun fromLoader(resource: String, classLoader: ClassLoader, locale: Locale) : ErrorResource {
val bundle = ResourceBundle.getBundle(resource, locale, classLoader)
return ErrorResource(bundle, locale)
}
}
private fun getProperty(propertyName: String) : String = bundle.getString(propertyName)
private fun formatTemplate(template: String, args: Array<Any>) : String {
val formatter = MessageFormat(template, locale)
return formatter.format(args)
}
fun getErrorMessage(args: Array<Any>): String {
val template = getProperty(MESSAGE_TEMPLATE)
return formatTemplate(template, args)
}
val shortDescription: String = getProperty(SHORT_DESCRIPTION)
val actionsToFix: String = getProperty(ACTIONS_TO_FIX)
val aliases: String = getProperty(ALIASES)
}

View File

@ -0,0 +1,20 @@
package net.corda.common.logging.errorReporting
/**
* Namespaces for errors within the node.
*/
enum class NodeNamespaces {
DATABASE
}
/**
* Errors related to database connectivity
*/
enum class NodeDatabaseErrors : ErrorCodes {
COULD_NOT_CONNECT,
MISSING_DRIVER,
FAILED_STARTUP,
PASSWORD_REQUIRED_FOR_H2;
override val namespace = NodeNamespaces.DATABASE.toString()
}

View File

@ -0,0 +1,11 @@
package net.corda.common.logging.errorReporting
/**
* Constants defining the properties available in the resource bundle files.
*/
object ResourceBundleProperties {
const val MESSAGE_TEMPLATE = "errorTemplate"
const val SHORT_DESCRIPTION = "shortDescription"
const val ACTIONS_TO_FIX = "actionsToFix"
const val ALIASES = "aliases"
}

View File

@ -0,0 +1,2 @@
errorCodeMessage = Error Code: {0}
errorCodeUrl = For further information, please go to {0}

View File

@ -0,0 +1,2 @@
errorCodeMessage = Error Code: {0}
errorCodeUrl = For further information, please go to {0}

View File

@ -0,0 +1,4 @@
errorTemplate = Could not connect to the database. Please check your JDBC connection URL, or the connectivity to the database.
shortDescription = The node failed to connect to the database on node startup, preventing the node from starting correctly.
actionsToFix = This happens either because the database connection has been misconfigured or the database is unreachable. Check that the JDBC URL is configured correctly in your node.conf. If this is correctly configured, then check your database connection.
aliases =

View File

@ -0,0 +1,3 @@
errorTemplate = Could not connect to the database. Please check your JDBC connection URL, or the connectivity to the database.
shortDescription = The node failed to connect to the database on node startup, preventing the node from starting correctly.
actionsToFix = This happens either because the database connection has been misconfigured or the database is unreachable. Check that the JDBC URL is configured correctly in your node.conf. If this is correctly configured, then check your database connection.

View File

@ -0,0 +1,4 @@
errorTemplate = Failed to create the datasource. See the logs for further information and the cause.
shortDescription = The datasource could not be created for unknown reasons.
actionsToFix = The logs in the logs directory should contain more information on what went wrong.
aliases =

View File

@ -0,0 +1,3 @@
errorTemplate = Failed to create the datasource. See the logs for further information and the cause.
shortDescription = The datasource could not be created for unknown reasons.
actionsToFix = The logs in the logs directory should contain more information on what went wrong.

View File

@ -0,0 +1,4 @@
errorTemplate = Could not find the database driver class. Please add it to the 'drivers' folder.
shortDescription = The node could not find the driver in the 'drivers' directory.
actionsToFix = Please ensure that the correct database driver has been placed in the 'drivers' folder. The driver must contain the driver main class specified in 'node.conf'.
aliases =

View File

@ -0,0 +1,3 @@
errorTemplate = Could not find the database driver class. Please add it to the 'drivers' folder.
shortDescription = The node could not find the driver in the 'drivers' directory.
actionsToFix = Please ensure that the correct database driver has been placed in the 'drivers' folder. The driver must contain the driver main class specified in 'node.conf'.

View File

@ -0,0 +1,4 @@
errorTemplate = Database password is required for H2 server listening on {0}
shortDescription = A password is required to access the H2 server the node is trying to access, and this password is missing.
actionsToFix = Add the required password to the 'datasource.password' configuration in 'node.conf'.
aliases =

View File

@ -0,0 +1,3 @@
errorTemplate = Database password is required for H2 server listening on {0}
shortDescription = A password is required to access the H2 server the node is trying to access, and this password is missing.
actionsToFix = Add the required password to the 'datasource.password' configuration in 'node.conf'.

View File

@ -0,0 +1,20 @@
package net.corda.commmon.logging.errorReporting
import net.corda.common.logging.CordaVersion
import net.corda.common.logging.errorReporting.CordaErrorContextProvider
import org.junit.Test
import java.util.*
import kotlin.test.assertEquals
class CordaErrorContextProviderTest {
@Test(timeout = 300_000)
fun `check that correct URL is returned from context provider`() {
val context = CordaErrorContextProvider()
val expectedURL = "https://docs.corda.net/docs/corda-os/${CordaVersion.releaseVersion}/error-codes.html"
// In this first release, there is only one localisation and the URL structure for future localisations is currently unknown. As
// a result, the same URL is expected for all locales.
assertEquals(expectedURL, context.getURL(Locale.getDefault()))
assertEquals(expectedURL, context.getURL(Locale.forLanguageTag("es-ES")))
}
}

View File

@ -0,0 +1,122 @@
package net.corda.commmon.logging.errorReporting
import junit.framework.TestCase.assertEquals
import net.corda.common.logging.errorReporting.ErrorCode
import net.corda.common.logging.errorReporting.ErrorCodes
import net.corda.common.logging.errorReporting.ErrorContextProvider
import net.corda.common.logging.errorReporting.ErrorReporterImpl
import org.junit.After
import org.junit.Test
import org.junit.rules.TestName
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mockito
import org.slf4j.Logger
import java.text.DateFormat
import java.time.Instant
import java.util.*
class ErrorReporterImplTest {
companion object {
private const val TEST_URL = "test-url"
}
private val logs: MutableList<Any> = mutableListOf()
private val loggerMock = Mockito.mock(Logger::class.java).also {
Mockito.`when`(it.error(anyString())).then { logs.addAll(it.arguments) }
}
private val contextProvider: ErrorContextProvider = object : ErrorContextProvider {
override fun getURL(locale: Locale): String {
return "$TEST_URL/${locale.toLanguageTag()}"
}
}
private enum class TestNamespaces {
TEST
}
private enum class TestErrors : ErrorCodes {
CASE1,
CASE2,
CASE_3;
override val namespace = TestNamespaces.TEST.toString()
}
private val TEST_ERROR_1 = object : ErrorCode<TestErrors> {
override val code = TestErrors.CASE1
override val parameters = listOf<Any>()
}
private class TestError2(currentDate: Date) : ErrorCode<TestErrors> {
override val code = TestErrors.CASE2
override val parameters: List<Any> = listOf("foo", 1, currentDate)
}
private val TEST_ERROR_3 = object : ErrorCode<TestErrors> {
override val code = TestErrors.CASE_3
override val parameters = listOf<Any>()
}
private fun createReporterImpl(localeTag: String?) : ErrorReporterImpl {
val locale = if (localeTag != null) Locale.forLanguageTag(localeTag) else Locale.getDefault()
return ErrorReporterImpl("errorReporting", locale, contextProvider)
}
@After
fun tearDown() {
logs.clear()
}
@Test(timeout = 300_000)
fun `error codes logged correctly`() {
val error = TEST_ERROR_1
val testReporter = createReporterImpl("en-US")
testReporter.report(error, loggerMock)
assertEquals(listOf("This is a test message [Code: test-case1, URL: $TEST_URL/en-US]"), logs)
}
@Test(timeout = 300_00)
fun `error code with parameters correctly reported`() {
val currentDate = Date.from(Instant.now())
val error = TestError2(currentDate)
val testReporter = createReporterImpl("en-US")
testReporter.report(error, loggerMock)
val format = DateFormat.getDateInstance(DateFormat.LONG, Locale.forLanguageTag("en-US"))
assertEquals(listOf("This is the second case with string foo, number 1, date ${format.format(currentDate)} [Code: test-case2, URL: $TEST_URL/en-US]"), logs)
}
@Test(timeout = 300_000)
fun `locale used with no corresponding resource falls back to default`() {
val error = TEST_ERROR_1
val testReporter = createReporterImpl("fr-FR")
testReporter.report(error, loggerMock)
assertEquals(listOf("This is a test message [Code: test-case1, URL: $TEST_URL/fr-FR]"), logs)
}
@Test(timeout = 300_000)
fun `locale with corresponding resource causes correct error to be printed`() {
val error = TEST_ERROR_1
val testReporter = createReporterImpl("ga-IE")
testReporter.report(error, loggerMock)
assertEquals(listOf("Is teachtaireacht earráide é seo [Code: test-case1, URL: $TEST_URL/ga-IE]"), logs)
}
@Test(timeout = 300_000)
fun `locale with missing properties falls back to default properties`() {
val error = TEST_ERROR_1
val testReporter = createReporterImpl("es-ES")
testReporter.report(error, loggerMock)
assertEquals(listOf("This is a test message [Code: test-case1, URL: $TEST_URL/es-ES]"), logs)
}
@Test(timeout = 300_000)
fun `error code with underscore in translated to resource file successfully`() {
val error = TEST_ERROR_3
val testReporter = createReporterImpl("en-US")
testReporter.report(error, loggerMock)
assertEquals(listOf("This is the third test message [Code: test-case-3, URL: $TEST_URL/en-US]"), logs)
}
}

View File

@ -0,0 +1,2 @@
errorCodeMessage = Code: {0}
errorCodeUrl = URL: {0}

View File

@ -0,0 +1,2 @@
errorCodeMessage = Code: {0}
errorCodeUrl = URL: {0}

View File

@ -0,0 +1,4 @@
errorTemplate = This is the third test message
shortDescription = Test description
actionsToFix = Actions
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = This is the third test message
shortDescription = Test description
actionsToFix = Actions
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = This is a test message
shortDescription = Test description
actionsToFix = Actions
aliases = foo, bar

View File

@ -0,0 +1,3 @@
errorTemplate = This is a test message
shortDescription = Test description
actionsToFix = Actions

View File

@ -0,0 +1 @@
shortDescription = Descripci<EFBFBD>n de la prueba

View File

@ -0,0 +1,3 @@
errorTemplate = Is teachtaireacht earr<72>ide <20> seo
shortDescription = Teachtaireacht t<>st<73>la
actionsToFix = Roinnt gn<67>omhartha

View File

@ -0,0 +1,4 @@
errorTemplate = This is the second case with string {0}, number {1, number, integer}, date {2, date, long}
shortDescription = Test description
actionsToFix = Actions
aliases = ""

View File

@ -0,0 +1,4 @@
errorTemplate = This is the second case with string {0}, number {1, number, integer}, date {2, date, long}
shortDescription = Test description
actionsToFix = Actions
aliases =

View File

@ -0,0 +1,4 @@
errorTemplate = Seo an dara c<>s le sreang {0}, uimhir {1, uimhir, sl<73>nuimhir}, d<>ta {2, d<>ta, fada}
shortDescription = An dara tuairisc
actionsToFix = Roinnt gn<67>omhartha eile
aliases =