Skip to content

Commit

Permalink
Improved error handling related to the error mentioned in #69. And re…
Browse files Browse the repository at this point in the history
…factored all loggin to go through a central module for better maintenance going forward
  • Loading branch information
zachsa committed Mar 17, 2023
1 parent 1289b46 commit 497988a
Show file tree
Hide file tree
Showing 33 changed files with 200 additions and 151 deletions.
5 changes: 3 additions & 2 deletions src/api/src/config/_app.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { join, normalize, sep } from 'path'
import getCurrentDirectory from '../lib/get-current-directory.js'
import ensureDirectory from '../lib/ensure-directory.js'
import logger from '../lib/logger.js'

const __dirname = getCurrentDirectory(import.meta)
const p = (...args) => normalize(join(...args))
Expand Down Expand Up @@ -48,14 +49,14 @@ if (DEPLOYMENT_ENV === 'production') {
await ensureDirectory(MIGRATION_LOGS_DIRECTORY)
})().catch(error => {
if (FILES_DIRECTORY.includes('snapshot')) {
console.error(
logger.error(
'ERROR - missing application directory.',
'Please specify the FILES_DIRECTORY environment variable when starting the application',
`If you are executing this application via Powershell, try: $env:FILES_DIRECTORY="./assets"; .\\nccrd-win.exe'`,
error
)
} else {
console.error(
logger.error(
'ERROR - missing application directory.',
'Please create directory',
FILES_DIRECTORY,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mssql from 'mssql'
import logger from '../../../../lib/logger.js'

export default async (self, { input }, ctx) => {
const { pool } = ctx.mssql
Expand Down Expand Up @@ -68,7 +69,7 @@ export default async (self, { input }, ctx) => {

await transaction.commit()
} catch (error) {
console.error('Unable to assign roles to user', error)
logger.error('Unable to assign roles to user', error)
await transaction.rollback()
throw error
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import mssql from 'mssql'
import mergeTenantsSubmissions from '../../../../lib/sql/merge-tenants-submissions.js'
import logger from '../../../../lib/logger.js'

export default async (self, args, ctx) => {
const { pool } = ctx.mssql
Expand Down Expand Up @@ -28,7 +29,7 @@ export default async (self, args, ctx) => {

return submission
} catch (error) {
console.error('Unable to create submission', error)
logger.error('Unable to create submission', error)
await transaction.rollback()
throw error
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import mergeTenantsSubmissions from '../../../../lib/sql/merge-tenants-submissions.js'
import mssql from 'mssql'
import logger from '../../../../lib/logger.js'

export default async (_, { id }, ctx) => {
const { pool } = ctx.mssql
Expand All @@ -21,7 +22,7 @@ export default async (_, { id }, ctx) => {

await transaction.commit()
} catch (error) {
console.error('Error deleting tenants', id)
logger.error('Error deleting tenants', id)
await transaction.rollback()
throw error
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import mssql from 'mssql'
import { basename, sep, normalize, join } from 'path'
import { unlink } from 'fs'
import { IMAGES_DIRECTORY } from '../../../../config/index.js'
import logger from '../../../../lib/logger.js'

export default async (_, { ids }, ctx) => {
const { pool } = ctx.mssql
Expand Down Expand Up @@ -38,7 +39,7 @@ export default async (_, { ids }, ctx) => {
await new Promise((y, x) => unlink(p, e => (e ? x(e) : y())))
}
} catch (error) {
console.error('Unable to delete tenant assets. Clean up folder manually', error)
logger.error('Unable to delete tenant assets. Clean up folder manually', error)
}

// Delete user-role-tenant permissions for this tenant
Expand All @@ -54,7 +55,7 @@ export default async (_, { ids }, ctx) => {
await transaction.commit()
return ids
} catch (error) {
console.error('Error deleting tenants', ids)
logger.error('Error deleting tenants', ids)
await transaction.rollback()
throw error
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as migrations from './migrations/index.js'
import logger from '../../../../lib/logger.js'

export default async (self, { migration: key, input = {} }, ctx) => {
console.info('Running DB migration', key)
logger.info('Running DB migration', key)
const fn = migrations[key]

try {
Expand All @@ -12,7 +13,7 @@ export default async (self, { migration: key, input = {} }, ctx) => {
return false
}
} catch (error) {
console.error('Error running DB migration', key, error)
logger.error('Error running DB migration', key, error)
throw error
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { join } from 'path'
import { appendFile, unlink } from 'fs/promises'
import query, { DEV_QUERY_LIMIT } from './_query.js'
import { stringify } from 'csv'
import logger from '../../../../../../lib/logger.js'

export const csvFilePath = join(MIGRATION_LOGS_DIRECTORY, 'incorrect-submission-vocabularies.csv')

Expand Down Expand Up @@ -123,7 +124,7 @@ export default async (ctx, { tenantId }) => {
}),
})
} catch (error) {
console.error(`QUERY ERROR (project). key: ${field}. tree: ${tree}`, error.message)
logger.error(`QUERY ERROR (project). key: ${field}. tree: ${tree}`, error.message)
}
}

Expand All @@ -143,7 +144,7 @@ export default async (ctx, { tenantId }) => {
}),
})
} catch (error) {
console.error(`QUERY ERROR (mitigation). key: ${field}. tree: ${tree}`, error.message)
logger.error(`QUERY ERROR (mitigation). key: ${field}. tree: ${tree}`, error.message)
}
}

Expand All @@ -163,11 +164,11 @@ export default async (ctx, { tenantId }) => {
}),
})
} catch (error) {
console.error(`QUERY ERROR (adaptation). key: ${field}. tree: ${tree}`, error.message)
logger.error(`QUERY ERROR (adaptation). key: ${field}. tree: ${tree}`, error.message)
}
}
} catch (error) {
console.error('Unknown error occurred', error)
logger.error('Unknown error occurred', error)
} finally {
isRunning = false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { pool } from '../../../../../../mssql/pool.js'
import mssql from 'mssql'
import OL from 'ol/format/WKT.js'
import wkt from 'wkt'
import logger from '../../../../../../lib/logger.js'

/**
* The heatmap on the client shows that sometimes
Expand Down Expand Up @@ -65,7 +66,7 @@ export default async () => {
}

const correctedXy = wkt.stringify(correctedXy_)
console.info('Fixing', id, xy, correctedXy)
logger.info('Fixing', id, xy, correctedXy)
await transaction.request().input('id', id).input('xy', correctedXy).query(`
update Submissions
set project = JSON_MODIFY(project, '$.xy', @xy)
Expand All @@ -75,7 +76,7 @@ export default async () => {

await transaction.commit()
} catch (error) {
console.error('Unable to fix reverse coordinates (failed DB migration script)', error)
logger.error('Unable to fix reverse coordinates (failed DB migration script)', error)
await transaction.rollback()
throw error
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { pool } from '../../../../../../mssql/pool.js'
import mssql from 'mssql'
import wkt from 'wkt'
import logger from '../../../../../../lib/logger.js'

/**
* It's conventional to name geometry points as YX (Long/Lat)
Expand Down Expand Up @@ -62,15 +63,12 @@ export default async () => {
where
id = @id;`)

console.info('Updated Submissions.project', id)
logger.info('Updated Submissions.project', id)
}

await transaction.commit()
} catch (error) {
console.error(
'Unable to complete the yx => xy field migration. Rolling back transaction',
error
)
logger.error('Unable to complete the yx => xy field migration. Rolling back transaction', error)
await transaction.rollback()
throw error
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { unlink } from 'fs'
import mssql from 'mssql'
import logger from '../../../../lib/logger.js'

export default async (_, { ids, submissionId }, ctx) => {
const { pool } = ctx.mssql
Expand Down Expand Up @@ -52,7 +53,7 @@ export default async (_, { ids, submissionId }, ctx) => {

transaction.commit()
} catch (error) {
console.error('Error removing attachment', id, error)
logger.error('Error removing attachment', id, error)
await transaction.rollback()
transaction.rollback()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { pool } from '../../../../mssql/pool.js'
import mssql from 'mssql'
import mergeTenantSubmissions from '../../../../lib/sql/merge-tenants-submissions.js'
import logger from '../../../../lib/logger.js'

export default async (
_,
Expand Down Expand Up @@ -106,7 +107,7 @@ export default async (
await transaction.commit()
return result.recordset[0]
} catch (error) {
console.error('Error saving submission', submissionId)
logger.error('Error saving submission', submissionId)
await transaction.rollback()
throw error
}
Expand Down
3 changes: 2 additions & 1 deletion src/api/src/graphql/resolvers/queries/chart/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import * as charts from './chart-types/index.js'
import logger from '../../../../lib/logger.js'

export default async (self, { id }, ...props) => {
const fn = charts[id]

try {
return { id, data: await fn(...props) }
} catch (error) {
console.error('Error creating chart', id, error.message)
logger.error('Error creating chart', id, error.message)
throw error
}
}
3 changes: 2 additions & 1 deletion src/api/src/graphql/schema/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
mitigationVocabularyFields as _mitigationVocabularyFields,
adaptationVocabularyFields as _adaptationVocabularyFields,
} from './vocabulary-fields.js'
import logger from '../../lib/logger.js'

const __dirname = getCurrentDirectory(import.meta)

Expand All @@ -34,7 +35,7 @@ const schema = makeExecutableSchema({
inheritResolversFromInterfaces: true,
})

console.info('Building input type fields list from GraphQL schema')
logger.info('Building input type fields list from GraphQL schema')
const typeFields = graphqlSync({
schema,
source: print(
Expand Down
3 changes: 2 additions & 1 deletion src/api/src/graphql/schema/vocabulary-fields.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { readFileSync, readdirSync } from 'fs'
import { join } from 'path'
import getCurrentDirectory from '../../lib/get-current-directory.js'
import getVocabularyFields from './_get-vocabulary-fields-from-input-type.js'
import logger from '../../lib/logger.js'

const __dirname = getCurrentDirectory(import.meta)

Expand All @@ -21,7 +22,7 @@ const _import = p =>

const typeDefs = SCHEMA_PARTS.map(name => `${_import(`./type-defs/${name}`)}`).join('\n')

console.info('Building vocabularies field list from Graphql schema definitions')
logger.info('Building vocabularies field list from Graphql schema definitions')
export const projectVocabularyFields = getVocabularyFields(typeDefs, 'ProjectInput')
export const mitigationVocabularyFields = getVocabularyFields(typeDefs, 'MitigationInput')
export const adaptationVocabularyFields = getVocabularyFields(typeDefs, 'AdaptationInput')
3 changes: 2 additions & 1 deletion src/api/src/http/create-tenant/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { IMAGES_DIRECTORY } from '../../config/index.js'
import { createReadStream, createWriteStream } from 'fs'
import mergeTenantsSubmissions from '../../lib/sql/merge-tenants-submissions.js'
import sanitize from 'sanitize-filename'
import logger from '../../lib/logger.js'

/**
* Creates the new tenant
Expand Down Expand Up @@ -152,7 +153,7 @@ export default async ctx => {

ctx.body = JSON.stringify(tenant)
} catch (error) {
console.error('Unable to create tenant', error)
logger.error('Unable to create tenant', error)
await transaction.rollback()
if (error.message.includes('Violation of UNIQUE KEY constraint')) {
ctx.throw(409)
Expand Down
4 changes: 2 additions & 2 deletions src/api/src/http/download-flagged-vocabularies/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createReadStream } from 'fs'
import { basename } from 'path'

import logger from '../../lib/logger.js'
import { csvFilePath } from '../../graphql/resolvers/mutations/migrate-database/migrations/find-incorrect-submission-vocabularies/index.js'

export default async ctx => {
Expand All @@ -9,7 +9,7 @@ export default async ctx => {
ctx.body = createReadStream(csvFilePath)
ctx.attachment(basename(csvFilePath))
} catch (error) {
console.error('Error retrieving submission file', error.message)
logger.error('Error retrieving submission file', error.message)
ctx.throw(404)
}
}
3 changes: 2 additions & 1 deletion src/api/src/http/download-public-file/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { pool } from '../../mssql/pool.js'
import { createReadStream } from 'fs'
import { basename } from 'path'
import logger from '../../lib/logger.js'

export default async ctx => {
const { fileId } = ctx.query
Expand All @@ -22,7 +23,7 @@ export default async ctx => {
ctx.body = createReadStream(filePath)
ctx.attachment(basename(filePath))
} catch (error) {
console.error('Error retrieving submission file', error.message)
logger.error('Error retrieving submission file', error.message)
ctx.throw(404)
}
}
7 changes: 4 additions & 3 deletions src/api/src/http/download-submissions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import makeHeaderRow from './make-header-row/index.js'
import { stringify as stringifySync } from 'csv/sync'
import buildSearchSql from './build-search-sql/index.js'
import logSql from '../../lib/log-sql.js'
import logger from '../../lib/logger.js'

const csvOptions = {
delimiter: ',',
Expand Down Expand Up @@ -139,7 +140,7 @@ export default async ctx => {
})

request.on('error', error => {
console.error(
logger.error(
'Error generating download for IDs or search',
ids?.join(';') || JSON.stringify(search),
error.message
Expand All @@ -161,11 +162,11 @@ export default async ctx => {
insert into DownloadLog (userId, submissionIds, submissionSearch)
values (@userId, @submissionIds, @submissionSearch);`)
} catch (error) {
console.error('Error logging download', error.message)
logger.error('Error logging download', error.message)
}
})
} catch (error) {
console.error(error.message)
logger.error(error.message)
ctx.response.status = 404
}
}
Loading

0 comments on commit 497988a

Please sign in to comment.