ParseServer UnhandledPromiseRejectionWarning: Unhandled promise rejection - parse-server

I just upgrade parse-server to 3.0.0,js-sdk to 2.1.0.
Parse.Cloud.define('delete_account', function(request) {
var user = request.user;
user.set("delete",true);
user.save(null,{useMasterKey:true}).then(function(user){
return "account deleted,please logout";
}).catch(function (reason) {
throw "delete fail";
});
when i call the function it says:
(node:27120) UnhandledPromiseRejectionWarning: delete fail
(node:27120) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Related

How can I catch errors in middleware on nestjs

I am trying to catch errors with try-catch structure in middleware. I call next function in try block and if I have an error like null reference etc., I wait to catch the error in catch block. But it is not working.
export function GlobalMiddleware(req: Request, res: Response, next: NextFunction) {
try {
next();
} catch (error) {
console.log(error);
}
}
According to the documentation, catching all unhandled exceptions can be done using an exception filter.
You can learn more about how to use a global exception filter on the documentation as there is a section about it: https://docs.nestjs.com/exception-filters#catch-everything

Why if i created a mock i am still getting error?

i am doing testing, i made a test in that test i create a mock for a fake function
jest.mock('#/services/myService', ()=>({getAvailables: jest.fn().mockReturnValue()}))
that function is running in my component
onMounted(async () => {
const answer = await getAvailables1()
const answer = await getAvailables2()
const answer = await getAvailables3()
but still i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables1) is not a function
(node:81921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag
if i put like this first getAvailables2
onMounted(async () => {
const answer = await getAvailables2()
const answer = await getAvailables1()
i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables2) is not a function
if i put like this first getAvailables3
onMounted(async () => {
const answer = await getAvailables3()
const answer = await getAvailables2()
i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables3) is not a function
also i try with mockResolvedValue, does not worked
export const getAvailables = async () => {
let response
let error
try {
response = await getData()
} catch (err) {
error = err
throw err
}
return { response, error }
}
It looks like you want a mock partial:
jest.mock('#/services/myService', () => {
const originalModule = jest.requireActual('#/services/myService');
return {
__esModule: true,
...originalModule,
getAvailables1: () => Promise.resolve({ foo: 'bar' }),
getAvailables2: () => Promise.resolve({ foo: 'baz' }),
getAvailables3: () => Promise.resolve({ foo: 'bad' }),
/* any other method of your service that gets called */
};
});
This will mock the provided functions in the mock while the rest of the service will function as in the original.
getAvailables() is async function that always returns a promise.
So, in order to mock that function you need to return the mock promise with success or rejected value.
Following is the example of mocking that function which returns success promise.
jest.mock('#/services/myService', () => ({
getAvailables: jest.fn().mockResolvedValue(true)
}))

How to test a function in a catch block of try/catch?

I have a custom package that is called if an error is thrown in the catch block of a try/catch. I want to test that the logFunction.error function is called. How do I test this function in the catch block? I'm passing in a mock jwt. I'm using jwtDcode (https://www.npmjs.com/package/jwt-decode) to decode my jwt. If it fails, an error is thrown the logFunction.error() returns a details object. Is this the correct way to set up this unit test?
file.js
jwtFunction ({commit}, idToken) {
try {
jwtDecode(idToken)
// do some logic
}catch (error) {
logFunction.error({
details: {
event: 'invalid jwt'
message: `${error.message} of ${idToken}`
timeStamp: Date.now()
}
})
commit(types.setApplicationError, error)
}
file.spec.js
it('[positive] should commit application error if jwt fails to decode', () => {
const mockIdToken = {}
const spy = jest.spyOn(logFunction, 'error')
actions.jwtFunction({ commit }, mockIdToken)
expect(spy).toHaveBeenCalled()
})

Nuxt.js - 'error not defined' when trying to throw 404 in failed await call within asyncData method

Starting to play with Nuxt.js this evening and mock blog data but having an issue with non existing data.
Heres my asyncData method when viewing a single blog post:
async asyncData({ params }) {
try {
const post = await axios.get(
`https://jsonplaceholder.typicode.com/posts/${params.id}`
)
return {
post: post.data
}
} catch (err) {
error({ statusCode: 404, message: 'Post not found' })
}
}
When visiting a valid ID and a 200 error is returned everything works as expected, but when the endpoint returns a 404 it tells me that 'error is undefined'
I could only find information on doing this error handling using a promise catch method as seen here: https://nuxtjs.org/guide/async-data/#handling-errors
How can I use the error method within the try catch error?
Thanks.
You have to inject the error object in your asyncData method to use it inside:
async asyncData({ error, params }) {
// your code
}

Asynchronous controller in Express for Form parsing to Mongoose

Currently, I'm developing a way to upload a message (file and fields) from Dropzone to Mongoose using Express Router. My back-end controller (which is called after authentication and data validation) goes as follows:
//Import Internal Dependencies
const Loader = require('../models/loader.js');
const Formidable = require('formidable');
const fs = require('fs');
module.exports = {
load: async (req, res, next) => {
var form = new Formidable.IncomingForm();
let path;
let contentType;
await form.parse(req, async function (err, fields, files) {
if (err) {
return res.status(404).json(err);
} else {
const {
user,
patient,
condition,
compound,
classi
} = fields;
path = files.image.path;
contentType = files.image.type;
fs.readFile(path, async function (err, data) {
if (err) {
return res.status(404).json(err);
} else {
//Save load
const newLoader = new Loader({
user,
patient,
condition,
compound,
classi,
image: {
data,
contentType
}
});
//Delete image in local storage
await fs.unlink(path, function (error) {
if(error){
return res.status(404).json(error)
}
});
await newLoader.save();
res.status(200).json("Load image sucessfully.");
next()
}
})
}
});
}
};
When I test it with Postman I got a status 202 and images are successfully upload to the database. However, when I try to upload with dropzone without the fields (which should cause some error and be displayed in dropzone) I got the following errors/warning in the back-end console (Dropzone stoped at upload and didn't show any error):
(node:20834) UnhandledPromiseRejectionWarning: ValidationError: load validation failed: user: Path `user` is required., classi: Path `classi` is required.
at new ValidationError (/root/aimuneBack/node_modules/mongoose/lib/error/validation.js:27:11)
at model.Document.invalidate (/root/aimuneBack/node_modules/mongoose/lib/document.js:1876:32)
at p.doValidate.skipSchemaValidators (/root/aimuneBack/node_modules/mongoose/lib/document.js:1744:17)
at /root/aimuneBack/node_modules/mongoose/lib/schematype.js:808:9
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
(node:20834) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20834) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
at emitWarning (internal/process/promises.js:92:15)
at emitPendingUnhandledRejections (internal/process/promises.js:109:11)
at process._tickCallback (internal/process/next_tick.js:189:7)
POST /load - - ms - -
So I know I have done something wrong with my asynchronous code and unfortunately cannot figure it out. Hope you can help. Best regards, Andre