I have the below code to throw an exception from Apex
#AuraEnabled()
public static void associateAccount(string userId, string accountSAPNumber) {
if(String.isBlank(userId) || string.isBlank(accountSAPNumber)) {
throw new AuraHandledException('Please specify both User Email2 and SAP Number2');
}
List<user> users = [SELECT Id, Name,Email FROM User WHERE Email =: userId AND IsActive = true AND Profile.Name ='OEA Customer'];
if(users == null || users.size() <= 0) {
NoDataFoundException noUsersFound = new NoDataFoundException();
noUsersFound.setMessage('No users found with the specified email address: ' + userId);
throw noUsersFound;
}
Id accountRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('OEA Customer Location').getRecordTypeId();
accountSAPNumber = '%' + accountSAPNumber;
List<Account> accounts = [SELECT Id FROM Account WHERE RecordTypeId =:accountRecordTypeId AND SAP_Number__c like :accountSAPNumber];
if(accounts == null || accounts.size() <= 0) {
NoDataFoundException noAccountFound = new NoDataFoundException();
noAccountFound.setMessage('No accounts found with the specified SAP Number: ' + accountSAPNumber);
throw noAccountFound;
}
else if(accounts.size() > 1) {
SearchException moreThan1Account = new SearchException();
moreThan1Account.setMessage('More than 1 account found with the specified SAP Number: ' + accountSAPNumber);
throw moreThan1Account;
}
OEA_NewContactFormController.accountMethod(userId, accountSAPNumber);
}
I am not able to catch this exception in my LWC Controller using the below
continueButtonClicked() {
associateAccount({
userId: this.searchKey,
accountSAPNumber: this.accountNumber,
})
.then((result) => {
try {
console.log("return from remote call " + result);
this.modalPopUpToggleFlag = false;
} catch (error) {
console.log('some error');
}
})
.error((error) => {
console.log("some error in code");
/*if (Array.isArray(error.body)) {
console.log(
"error message :" + error.body.map((e) => e.message).join(", ")
);
} else if (typeof error.body.message === "string") {*/
//console.log("error message :" + error);
//}
})
.finally(() => {
console.log("finally message :");
});
}
This always gives me an error on the console as "Uncaught (in promise)" and with the details of the exception. How can I catch this exception in a handled way.
The correct syntax is .then().catch().finally(), while you wrote .then().error().finally().
Moreover associateAccount returns void, so there will be no result received from then. There is also no reason to wrap this.modalPopUpToggleFlag = false; in a try-catch, only if your never defined modalPopUpToggleFlag there could be an error.
continueButtonClicked() {
associateAccount({
userId: this.searchKey,
accountSAPNumber: this.accountNumber,
})
.then(() => {
console.log("return from remote call);
this.modalPopUpToggleFlag = false;
})
.catch((error) => {
console.log("some error in code:", error);
});
}
Here is a good reading about Using Promises in Javascript
I'm trying to code a bot command using discord.js and Minecraft-server-util but my code is not using the const I defined and is saying it does not exist. If you spot any other problems you can correct me on them.
client.on('message', message => {
if (message.content === `${prefix}javaserverstatus`) {
const args = message.content.slice(prefix.length).trim().split(' '); // this is where args is defined.
if (!args.length) {
return message.channel.send(`You didn't provide a server, ${message.author}!`); // checks if args exist
}
if (args.length > 1) {
return message.channel.send(`Wrong input! EG. play.hypixel.net, ${message.author}`); // checks if there are only 1 arguments
}
}
const util = require('minecraft-server-util');
var serverinfo = null
util.status(args) // This code is giving an error saying args does not exist.
.then((response) => {
console.log(response);
serverinfo = response;
const embed = new Discord.MessageEmbed()
.setTitle('play.hypixel.net Server Status')
.setColor(0xff0000)
.setDescription('IP: ' + response.host + '\n' + 'Port: ' + response.port + '\n' + 'Version: ' + response.version + '\n' + 'Online Players: ' + response.onlinePlayers.toString() + '\n' + 'Max Players: ' + response.maxPlayers.toString() + '\n');
message.channel.send(embed);
})
.catch((error) => {
console.error(error);
});
});
The error is due to the scope that you've defined args in.
args is defined in your first if statement when it should be defined a line above.
const args = message.content.slice(prefix.length).trim().split(' ');
if (message.content === `${prefix}javaserverstatus`) {
// this is where args is defined.
if (!args.length) {
return message.channel.send(`You didn't provide a server, ${message.author}!`); // checks if args exist
}
if (args.length > 1) {
return message.channel.send(`Wrong input! EG. play.hypixel.net, ${message.author}`); // checks if there are only 1 arguments
}
}
You've defined args in a if statement. You need to put it out of there.
client.on('message', (message) => {
const args = message.content.slice(prefix.length).trim().split(' ') // this is where args is defined.
if (message.content === `${prefix}javaserverstatus`) {
if (!args.length) {
return message.channel.send(`You didn't provide a server, ${message.author}!`) // checks if args exist
}
if (args.length > 1) {
return message.channel.send(`Wrong input! EG. play.hypixel.net, ${message.author}`) // checks if there are only 1 arguments
}
}
const util = require('minecraft-server-util')
var serverinfo = null
util
.status(args) // This code is giving an error saying args does not exist.
.then((response) => {
console.log(response)
serverinfo = response
const embed = new Discord.MessageEmbed()
.setTitle('play.hypixel.net Server Status')
.setColor(0xff0000)
.setDescription('IP: ' + response.host + '\n' + 'Port: ' + response.port + '\n' + 'Version: ' + response.version + '\n' + 'Online Players: ' + response.onlinePlayers.toString() + '\n' + 'Max Players: ' + response.maxPlayers.toString() + '\n')
message.channel.send(embed)
})
.catch((error) => {
console.error(error)
})
})
If this isn't working, pls send me the command you sent in the discord chat.
I am working on a code that sends a random picture from a subreddit, from the weekly top.
But I receive the following error when I am trying to use the command:
(node:25) UnhandledPromiseRejectionWarning: RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty.
Code:
client.on("message", async message => {
if (message.content.toLowerCase() === "!foto") {
const snekfetch = require('snekfetch');
try {
const {
body
} = await snekfetch
.get('https://www.reddit.com/r/gtavcustoms.json?sort=top&t=week')
.query({
limit: 10
});
const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
if (!allowed.length) return message.channel.send('Het lijkt erop dat de nieuwe fotos op zijn, probeer het later nog eens!');
const randomnumber = Math.floor(Math.random() * allowed.length)
const embed = new Discord.MessageEmbed()
.setColor(0x00A2E8)
.setTitle(allowed[randomnumber].data.title)
.setDescription("Gepost door: " + allowed[randomnumber].data.author)
.setImage(allowed[randomnumber].data.url)
.addField("Overige informatie:", "Likes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
.setFooter("DaddyCoolNL Official Discord Server")
message.channel.send(embed)
} catch (err) {
return console.log(err);
}
}
});
This may be a simple fix, but may not work. What you can try is putting it in backticks.
.addField("Overige informatie:", `Likes: ${allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)}`
It also may be due to the allowed array not being complete, or something is off with it.
I try to set the member roles, but it doesn't set the permissions.
My index.js file:
var u, s, m;
await bot.users.fetch(message.author.id)
.then(user => { u = user; });
await bot.guilds.fetch('419248578121433100')
.then(guild => { s = guild; });
await s.members.fetch(u)
.then(member => { m = member; });
axios.get('/process')
.then(function (response)
{
var dptos = response.data.dptos;
var attrs = response.data.userAttrs;
var roles = response.data.roles;
if(dptos.length > 0) m.setNickname(dptos[0].position + ' | ' + attrs.name + ' ' + attrs.surname);
else m.setNickname(attrs.name + ' ' + attrs.surname + ' | ' + '123456');
m.roles.set(roles)
.then(function(member)
{
let fd = fs.openSync('log.txt', 'w');
fs.writeSync(fd, JSON.stringify(member.roles.cache));
fs.closeSync(fd);
})
.catch(function(error)
{
let fd = fs.openSync('error.txt', 'w');
fs.writeSync(fd, error);
fs.closeSync(fd);
});
return message.reply('Congrats!');
})
.catch(function (error)
{
return message.reply('error!');
});
}
The axios request works as expected and the data is obtained correctly.
Screenshots:
Bot position
Bot general permissions
UPDATE 1: Nickname permissions
What could be the issue?
I am trying to get the contents of a .json file using a node js service into an angularjs method. But am getting following error:
_http_outgoing.js:700
throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object
at ServerResponse.end (_http_outgoing.js:700:13)
here are the corresponding code fragments...
angular controller: the commented lines are all of those which i have tried and failed with.
var currentProcess = "process_1cA";
$scope.storestats = [];
var resAss = $resource('/procs/getstorestats');
var stats = resAss.get({
process: currentProcess,
date: date.getFullYear() + "" + m + "" + d
});
stats.$promise.then(function(response) {
if (response != undefined) {
// var r = JSON.parse(response);
//$scope.storestats.push(r);
//$scope.storestats.push(r);
//var r = JSON.parse(response);
$scope.storestats.push(response);
//angular.forEach(r, function(value, key) {
// $scope.storestats.push({key : value});
//});
}
});
NODEJs service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.end(msgs1);
});
}
catch (err) {
res.end(err.toString());
}});
P.S: The commented out lines are those which i have tried out with and failed. Also, the commented lines in the node service code snippet, give no error, and when logged show it correctly, but the data when in response of the controllers is blank.
I'm guessing a bit here, but I think you just need to change res.end() to res.send() in your Node code. The "end" method is used when you are streaming chunks of data and then you call end() when you're all done. The "send" method is for sending a response in one go and letting Node handle the streaming.
Also, be sure you are sending a string back!
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.send(msgs2); // NOTE THE CHANGE to `msg2` (the string version)
});
}
catch (err) {
res.send(err.toString()); // NOTE THE CHANGE
}
});
I had a similar error. It was because I was passing process.pid to res.end(). It worked when I changed process.pid to string
res.end(process.pid.toString());
Figured it out. 2 small changes were needed.. One in the controller, which was to use a "$resource.query" instead of "$resource.get". And in the service, as #jakarella said, had to use the stringified part in the .end();
Controller:
var resAss = $resource('/procs/getstorestats');
var stats = resAss.query({process: currentProcess, date: date.getFullYear() + "" + m + "" + d});
stats.$promise.then(function (response) {
$scope.storestats.push(response);
}
Node Service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
var msgs2 = JSON.stringify(msgs1);
console.log(msgs2);
res.end(msgs2);
});
}
If you are using 'request-promise' library set the json
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
})
.catch(function (err) {
});
Thank you user6184932, it work
try {
await insertNewDocument(fileNameDB, taskId);
res.end(process.pid.toString());
} catch (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
in mysql2 the reason for the error is the sql word , sql is a query :
const sql = select * from tableName
pool.executeQuery({
sql,
name: 'Error list for given SRC ID',
values: [],
errorMsg: 'Error occurred on fetching '
})
.then(data => {
res.status(200).json({ data })
})
.catch(err => {
console.log('\n \n == db , icorp fetching erro ====> : ', err.message, '\n \n')
})
I got the error using Node v12 (12.14.1).
Uncaught TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number
Sample code for context.
const { Readable } = require('stream')
Readable.from(Buffer.from(base64content, 'base64'))
.pipe( ... )
Solution (for my case), was upgrading to Node v14 (14.17.3). e.g.
nvm use 14
nvm