Skip to content

Commit

Permalink
feat: add rethrow functions (#425)
Browse files Browse the repository at this point in the history
* feat: add rethrow functions

* chore(snapshot): 18.15.0-snapshot.0

* feat: add rethrow functions

* chore(snapshot): 18.15.0-snapshot.1

* chore: change log

* chore: change log
  • Loading branch information
kleyow authored Jan 6, 2025
1 parent 2fad121 commit 82758d4
Show file tree
Hide file tree
Showing 8 changed files with 299 additions and 41 deletions.
28 changes: 14 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@mojaloop/central-services-shared",
"version": "18.14.2",
"version": "18.15.0-snapshot.1",
"description": "Shared code for mojaloop central services",
"license": "Apache-2.0",
"author": "ModusBox",
Expand Down Expand Up @@ -68,7 +68,7 @@
"event-stream": "4.0.1",
"fast-safe-stringify": "^2.1.1",
"immutable": "5.0.3",
"ioredis": "^5.4.1",
"ioredis": "^5.4.2",
"lodash": "4.17.21",
"mustache": "4.2.0",
"openapi-backend": "5.11.1",
Expand All @@ -78,15 +78,15 @@
"ulidx": "2.4.1",
"uuid4": "2.0.3",
"widdershins": "^4.0.1",
"yaml": "2.6.1"
"yaml": "2.7.0"
},
"devDependencies": {
"@hapi/hapi": "21.3.12",
"@hapi/joi": "17.1.1",
"audit-ci": "^7.1.0",
"base64url": "3.0.1",
"chance": "1.1.12",
"npm-check-updates": "17.1.11",
"npm-check-updates": "17.1.13",
"nyc": "17.1.0",
"portfinder": "1.0.32",
"pre-commit": "1.2.2",
Expand Down
4 changes: 3 additions & 1 deletion src/util/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const OpenapiBackend = require('./openapiBackend')
const id = require('./id')
const config = require('../config')
const { loggerFactory } = require('@mojaloop/central-services-logger/src/contextLogger')
const rethrow = require('./rethrow')

const omitNil = (object) => {
return _.omitBy(object, _.isNil)
Expand Down Expand Up @@ -265,5 +266,6 @@ module.exports = {
Schema,
OpenapiBackend,
id,
resourceVersions: Helpers.resourceVersions
resourceVersions: Helpers.resourceVersions,
rethrow
}
23 changes: 10 additions & 13 deletions src/util/kafka/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const Enum = require('../../enums')
const StreamingProtocol = require('../streaming/protocol')
const ErrorHandler = require('@mojaloop/central-services-error-handling')
const EventSdk = require('@mojaloop/event-sdk')

const { rethrowKafkaError } = require('../rethrow')
/**
* @function ParticipantTopicTemplate
*
Expand All @@ -59,8 +59,7 @@ const participantTopicTemplate = (template, participantName, functionality, acti
action
})
} catch (err) {
Logger.isErrorEnabled && Logger.error(err)
throw ErrorHandler.Factory.reformatFSPIOPError(err)
rethrowKafkaError(err)
}
}

Expand All @@ -79,8 +78,7 @@ const generalTopicTemplate = (template, functionality, action) => {
try {
return Mustache.render(template, { functionality, action })
} catch (err) {
Logger.isErrorEnabled && Logger.error(err)
throw ErrorHandler.Factory.reformatFSPIOPError(err)
rethrowKafkaError(err)
}
}

Expand All @@ -102,8 +100,7 @@ const transformGeneralTopicName = (template, functionality, action) => {
}
return generalTopicTemplate(template, functionality, action)
} catch (err) {
Logger.isErrorEnabled && Logger.error(err)
throw ErrorHandler.Factory.reformatFSPIOPError(err)
rethrowKafkaError(err)
}
}

Expand All @@ -123,8 +120,7 @@ const transformAccountToTopicName = (template, participantName, functionality, a
try {
return participantTopicTemplate(template, participantName, functionality, action)
} catch (err) {
Logger.isErrorEnabled && Logger.error(err)
throw ErrorHandler.Factory.reformatFSPIOPError(err)
rethrowKafkaError(err)
}
}

Expand All @@ -148,7 +144,8 @@ const getKafkaConfig = (kafkaConfig, flow, functionality, action) => {
actionObject.config.logger = Logger
return actionObject.config
} catch (err) {
throw ErrorHandler.Factory.createInternalServerFSPIOPError(`No config found for flow='${flow}', functionality='${functionality}', action='${action}'`, err)
const error = ErrorHandler.Factory.createInternalServerFSPIOPError(`No config found for flow='${flow}', functionality='${functionality}', action='${action}'`, err)
rethrowKafkaError(error)
}
}

Expand Down Expand Up @@ -280,8 +277,7 @@ const commitMessageSync = async (kafkaConsumer, kafkaTopic, message) => {
await consumer.commitMessageSync(message)
} catch (err) {
Logger.isDebugEnabled && Logger.debug(`No consumer found for topic ${kafkaTopic}`)
Logger.isErrorEnabled && Logger.error(err)
throw err
rethrowKafkaError(err)
}
}
}
Expand All @@ -307,7 +303,8 @@ const proceed = async (defaultKafkaConfig, params, opts) => {
message.value.to = message.value.from

if (!opts.hubName) {
throw ErrorHandler.Factory.createInternalServerFSPIOPError('No hubName found in opts')
const error = ErrorHandler.Factory.createInternalServerFSPIOPError('No hubName found in opts')
rethrowKafkaError(error)
}

message.value.from = opts.hubName
Expand Down
10 changes: 5 additions & 5 deletions src/util/redis/redisCache.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const Redis = require('ioredis')
const { createLogger } = require('../index')
const { REDIS_SUCCESS, REDIS_IS_CONNECTED_STATUSES } = require('../../constants')

const isClusterConfig = (config) => { return 'cluster' in config }
const { rethrowRedisError } = require('../rethrow')

class RedisCache {
constructor (config, client) {
Expand Down Expand Up @@ -78,7 +78,7 @@ class RedisCache {
return await this.redisClient.get(key)
} catch (err) {
this.log.error('Error getting key from Redis:', err)
throw err
rethrowRedisError(err)
}
}

Expand All @@ -91,7 +91,7 @@ class RedisCache {
}
} catch (err) {
this.log.error('Error setting key in Redis:', err)
throw err
rethrowRedisError(err)
}
}

Expand All @@ -100,7 +100,7 @@ class RedisCache {
await this.redisClient.del(key)
} catch (err) {
this.log.error('Error deleting key from Redis:', err)
throw err
rethrowRedisError(err)
}
}

Expand All @@ -112,7 +112,7 @@ class RedisCache {
await pipeline.exec()
} catch (err) {
this.log.error('Error clearing Redis cache:', err)
throw err
rethrowRedisError(err)
}
}
}
Expand Down
112 changes: 112 additions & 0 deletions src/util/rethrow.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*****
License
--------------
Copyright © 2020-2024 Mojaloop Foundation
The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Contributors
--------------
This is the official list of the Mojaloop project contributors for this file.
Names of the original copyright holders (individuals or organizations)
should be listed with a '*' in the first column. People who have
contributed from an organization can be listed under the organization
that actually holds the copyright for their contributions (see the
Mojaloop Foundation for an example). Those individuals should have
their names indented and be marked with a '-'. Email address can be added
optionally within square brackets <email>.
* Mojaloop Foundation
- Name Surname <[email protected]>
* Infitx
- Kevin Leyow <[email protected]>
--------------
******/

const ErrorHandler = require('@mojaloop/central-services-error-handling')
const Metrics = require('@mojaloop/central-services-metrics')

const { logger } = require('../logger')

/**
* Rethrows an FSPIOP error after logging it and incrementing an error counter.
*
* @param {Error} error - The error to be rethrown.
* @param {Object} [options={}] - Optional parameters.
* @param {string} [options.operation] - The operation during which the error occurred.
* @param {string} [options.step] - The step during which the error occurred.
* @param {Object} [options.loggerOverride] - An optional logger to override the default logger.
* @throws {Error} - Throws the reformatted FSPIOP error.
*/
const rethrowAndCountFspiopError = (error, options = {}) => {
const { operation, step, loggerOverride } = options
const log = loggerOverride || logger
log.error(`rethrow fspiop error: ${error?.message}`)

const fspiopError = ErrorHandler.Factory.reformatFSPIOPError(error)
const extensions = fspiopError.extensions || []
const system = extensions.find((element) => element.key === 'system')?.value || ''

try {
const errorCounter = Metrics.getCounter('errorCount')
errorCounter.inc({
code: fspiopError?.apiErrorCode.code,
system,
operation,
step
})
} catch (error) {
log.error('Metrics error counter not initialized', error)
}

throw fspiopError
}

const constructSystemExtensionError = (error, system) => {
const extensions = [{
key: 'system',
value: system
}]
return ErrorHandler.Factory.reformatFSPIOPError(
error,
undefined,
undefined,
extensions
)
}

const rethrowError = (error, options = {}, system) => {
const { loggerOverride } = options
const log = loggerOverride || logger
log.error(`rethrow fspiop error: ${error?.message}`)
throw constructSystemExtensionError(error, system)
}

const rethrowDatabaseError = (error, options = {}) => {
rethrowError(error, options, '["db"]')
}

const rethrowCachedDatabaseError = (error, options = {}) => {
rethrowError(error, options, '["db","cache"]')
}

const rethrowRedisError = (error, options = {}) => {
rethrowError(error, options, '["redis"]')
}

const rethrowKafkaError = (error, options = {}) => {
rethrowError(error, options, '["kafka"]')
}

const rethrowCacheError = (error, options = {}) => {
rethrowError(error, options, '["cache"]')
}

module.exports = {
rethrowAndCountFspiopError,
rethrowDatabaseError,
rethrowCachedDatabaseError,
rethrowRedisError,
rethrowKafkaError,
rethrowCacheError,
constructSystemExtensionError
}
Loading

0 comments on commit 82758d4

Please sign in to comment.