Within a component, I have developed a function to manage errors returned from a Rest Service and determine the corresponding error message to display to the user. This method accepts an error object (custom data structure from the service), navigates to extract the relevant information, and then uses a switch statement to pass a JSON key for translation via an i18n service, as shown below:
private myErrorHandler(err: any): string {
// Why doesn't typescript support null-conditional?
if (err.error && err.error.errors && err.error.errors[0] && err.error.errors[0].error) {
const errorMsg = err.error.errors[0].error;
const errorValue = err.error.errors[0].value;
const translationArgs: any = { errorValue: null };
let correctMsg;
if (errorValue) {
translationArgs.errorValue = errorValue;
}
switch (errorMsg) {
case 'not_unique': {
correctMsg = errorValue ? 'common.validation.not_unique_value' : 'common.validation.not_unique';
break;
}
default: {
correctMsg = 'common.messages.global_error';
break;
}
}
return this.localizationService.translate(correctMsg, translationArgs as any);
}
return this.localizationService.translate('common.messages.global_error');
}
However, I face an issue when attempting to include some of the error data in the returned message as an argument. The code snippet below raises a TypeScript compiler error:
if (errorValue) {
translationArgs.errorValue = errorValue;
}
I seek guidance on how to resolve this linting error. I initially assumed that assigning a null value to the errorValue property in the translationArgs object would suffice, but it seems I was mistaken. Any suggestions will be highly appreciated.
I acknowledge that the method/function may not be structured optimally, so any feedback on this aspect is also welcome.
Below you can find the contents of my tsconfig file for reference:
{
"compilerOptions": {
"alwaysStrict": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"es6",
"dom"
],
"module": "commonjs",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"outDir": "dist",
"pretty": true,
"sourceRoot": "frontend",
"rootDir": "frontend",
"sourceMap": true,
"target": "es5",
"types": [
"node",
"mocha",
"chai",
"chai-as-promised",
"aws-sdk",
"q",
"sinon",
"file-saver"
],
"typeRoots": [
"./node_modules/@types"
]
},
"include": [
"frontend/**/*.ts"
],
"exclude": [
".git",
".idea",
"config",
"dist",
"e2e_tests",
"gulp",
"node_modules",
"reports",
"server",
"typings/browser.d.ts"
],
"awesomeTypescriptLoaderOptions": {
"useWebpackText": true
},
"angularCompilerOptions": {
"debug": false
},
"compileOnSave": false,
"buildOnSave": false,
"atom": {
"rewriteTsconfig": false
}
}