How do I extend the Error class? - node.js

This is my code:
let errorBadRequest = new Error("Bad request");
res.statusCode = 400;
errorBadRequest.errors = err.details.reduce(function(prev, current) {
prev[current.path] = current.message;
return prev;
}, {});
throw errorBadRequest;
I wanted to extend error attribute in error instance, but tsc said joi-utils.ts(21,23): error TS2339: Property 'errors' does not exist on type 'Error'.
The structure of errors is {fieldname: fieldmsg}, it's according to my joi request schema to decide.
How do I solve the error from typescript compiler? I think I need to declare a interface and be designate the attribute.

Property 'errors' does not exist on type 'Error'.
Create a file called error-extension.d.ts and have the following:
interface Error {
errors: Error;
}
More : https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html

I find when initialing the Error class, actually it hasn't errors in Error . It should make a interface and set errors to option.
This is my solution:
interface IJoiErrorException extends NodeJS.ErrnoException {
errors?: Object;
}
const errorBadRequest: IJoiErrorException = new Error("Bad request");

Related

when copy node js custom error class super Error variable is gone

I have a custom Err class that extends from Error class. all thing was good until I copy an instance of Err class. the super's variables of copied instance are undefined!
here is my code:
class Err extends Error {
constructor(code, msg) {
super(msg);
this.code = code;
}
}
const error = new Err(404, 'error message');
console.log(error);
/* { Error: error message
at repl:1:15
at Script.runInThisContext (vm.js:122:20)
at REPLServer.defaultEval (repl.js:332:29)
at bound (domain.js:402:14)
at REPLServer.runBound [as eval] (domain.js:415:12)
at REPLServer.onLine (repl.js:642:10)
at REPLServer.emit (events.js:203:15)
at REPLServer.EventEmitter.emit (domain.js:448:20)
at REPLServer.Interface._onLine (readline.js:308:10)
at REPLServer.Interface._line (readline.js:656:8) code: 404 }
*/
const copy = { ...error };
console.log(copy);
// { code: 404 }
// where is error.stack and error.name?
SOLUTION:
Change copy method to this
const copy= { ...error };
copy.name = error.name;
copy.message = error.message;
copy.stack = error.stack;
tanks PA.
if any one has a better solution tell it to me.
with copy = { ...error };
(1) the {} object literal operator, creates a new Object, not a new Err object,
and
(2) the ... or spread properties operator, for object literals, just copies the provided object own enumerable properties onto your new object.
To clone any javascript class instance with a perfect copy of properties, methods, getters/setters, non-enumerable properties, etc, ina a generic code is almost impossible. You may create your own copy/clone code for your particular case, with a combination of Object.assign() / Object.getPrototype() and custom tuning for inherited properties and internal classes.

TypeScript - Type undefined is not assignable to type ICustomType

I'm quite new to TypeScript and trying to understand what is the best way to approach such situation in my code.
I have array of objects that have a custom type in my system and I use Array.find method to get one of them. However I receive a compile error saying Type 'undefined' is not assignable to type IConfig.
Here's the code example -
const config: IConfig = CONFIGS.find(({ code }) => code === 'default');
// Type 'undefined' is not assignable to type IConfig
I tried to add undefined as possible type but then I get error on the next line which uses this object Object is possibly 'undefined', e.g. -
const config: IConfig | undefined = CONFIGS.find(({ code }) => code === 'default');
// Object is possibly 'undefined'
if (config.foo) {
return 'bar';
}
What is the best way to approach such type issues?
.find will return undefined if nothing in the array passes the callback test. If you're sure that default code exists in the array, then use the non-null assertion operator:
const config: IConfig = CONFIGS.find(({ code }) => code === 'default')!;
// ^
(If you weren't sure if it exists in the array, the warning you see is there to prompt you to explicitly test for if the item exists before trying to access a property on it, otherwise you'll sometimes get a runtime error:
const config: IConfig = CONFIGS.find(({ code }) => code === 'default');
if (!config) {
return 'No match found';
}
if (config.foo) {
return 'bar';
}
)

NodeJS - TypeError: Cannot read property 'name' of undefined

I am getting the following error from my code: If you could help me that would be amazing! I am using discord.js!
TypeError: Cannot read property 'name' of undefined at
files.forEach.file (/root/eternity-bot/eternity-bot/index.js:21:33) at
Array.forEach () at fs.readdir
(/root/eternity-bot/eternity-bot/index.js:18:9) at
FSReqWrap.oncomplete (fs.js:135:15)
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
if (!file.endsWith(".js")) return;
let props = require(`./commands/${file}`);
console.log(`Loading Command: ${props.help.name}.`);
bot.commands.set(props.help.name, props);
props.conf.aliases.forEach(alias => {
bot.aliases.set(alias, props.help.name);
})
});
});
TypeError: A TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function.
The possible cause is your props is not loaded correctly and doesn't include any property help, thus accessing property name of unknown property help throws TypeError. Similar to following:
let obj = {
o1: {
a: 'abc'
}
};
obj.o1 // gives {a: 'abc'}, as o1 is property obj which is an object.
obj.o1.a // gives 'abc', as a is property of o1, which is property of obj.
obj.o2 // undefined, as there's no o2 property in obj.
obj.o2.a // TypeError as there's no o2 property of obj and thus accessing property a of undefined gives error.
What is happening is that the code is working perfectly fine, but there seems to be some problem with the exports of your javascript files in the commands folder. Most probably, the help property is not defined in your files.

Typescript error TS2345 Error: TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'

new to Typescript. I am reading some data from RabbitMQ channel and am converting it to JSON object. In this line I get the error
let communicationInformation = JSON.parse(newCommunication.content);
TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'.
Do I need to cast the data? I am using Typescript 2.4.1
Amqplib.connect(amqpLibUrl, (err, connection) => {
if (!err) {
connection.createChannel((err, channel) => {
channel.consume('QueueName', newCommunication => {
if (newCommunication != null) {
let communicationInformation = JSON.parse(newCommunication.content);
// Code
}
})
})
}
});
I think the error is thrown on the input parameter of JSON.parse. Try to first call toString on it then pass to the function.
let communicationInformation = JSON.parse(newCommunication.content.toString());
I am not sure what is newCommunication.content. In my case it is a file and I had to specify encoding for fs.readFileSync:
const level = JSON.parse(fs.readFileSync('./path/to/file.json', 'utf-8'));
Next Error was error TS2531: Object is possibly 'null'.
You have to disable strictNullChecks in your compiler

Defining modules in UI5

I am trying to keep my code separated in modules. When I defined my first module I extended sap.ui.base.Object and it worked. My question is: Is it a must to extend sap.ui.base.Object when defining my own module? According to the API documentation I tried following example:
sap.ui.define([], function() {
// create a new class
var SomeClass = function();
// add methods to its prototype
SomeClass.prototype.foo = function() {
return "Foo";
}
// return the class as module value
return SomeClass;
});
I required this module inside my Component.js as dependency like this:
sap.ui.define([
"path/to/SomeClass"
], function (SomeClass) {
"use strict";
//var test = new SomeClass();
I always receive a syntax error:
failed to load '[...]/Component.js' from ./Component.js: Error: failed to load '[...]/module/SomeClass.js' from ./module/Service.js: SyntaxError: Unexpected token ;
Does anyone have an idea why this happens? Thanks!
We group code in modules like this for example:
jQuery.sap.declare("our.namespace.iscool.util.Navigation");
our.namespace.iscool.util.Navigation = {
to: function (pageId, context) {
// code here
}
// etc.
}
and call the function of the module like this in a controller
jQuery.sap.require("our.namespace.iscool.util.Navigation");
sap.ui.controller("our.namespace.iscool.Detail", {
// somewhere in this file comes this
handleNavButtonPress: function (evt) {
our.namespace.iscool.util.Navigation.navBackToMaster(
evt.getSource().getBindingContext()
);
},
}
Stupid mistake - missing curly brackets in the docs.
var someclass = function() {} ;

Resources