const functionName = async () => {
try {
//code
} catch (error) {
let data = {}
data.error = error
data.fnName = 'checkIfSupplierIsAllowedToSync'
throw new Error(data)
}
}
const fnName = async () => {
try {
await functionName()
} catch (error) {
console.log("error#####", error)
}
}
answer :-
error##### "[object Object]"
why i getting error in string ? how i get error with function name ?
Error expects a string to be passed to the constructor.
[object Object] is the string representation of the simple object that was passed in.
> {}.toString()
'[object Object]'
Create an error to attach the data to, rather then an object
const functionName = async () => {
try {
//code
} catch (error) {
const wrapped_error = new Error(`Wrapped: ${error.message}`)
wrapped_error.error = error
error.fnName = 'checkIfSupplierIsAllowedToSync'
throw wrapped_error
}
}
This could be added to an Error class that encapsulates the required behaviour
class WrappedError extends Error {
constructor(error, fnName) {
super(`Wrapped: ${error.message}`)
this.error = error
this.fnName = fnName
}
}
const functionName = async () => {
try {
//code
} catch (error) {
throw new WrappedError(error, 'checkIfSupplierIsAllowedToSync')
}
}
Related
I have a class A that is using another class(B)'s method. I am trying to write test for the class B and mocking the methods of the class A. But even if I mock, I am getting TypeError: this.A.getDynamoEntry is not a function. I have followed exactly the same steps given by the docs.
test.js file:
import A from '../../src/dao/A'
import B from '../../src/dao/B'
jest.mock('../../src/dao/A', () => {
return jest.fn().mockImplementation(() => {
return {
getDynamoEntry: jest.fn(()=> Promise.resolve(2)),
putDynamoEntry: jest.fn(),
updateDynamoEntry: jest.fn(),
deleteDynamoEntry: jest.fn()
};
});
});
beforeAll(() => {
initConfig()
})
describe('Test', () => {
let entity
beforeEach(() => {
entity = new B()
})
it('getFraudLogosByOwnerId', async () => {
const resp = await entity.getFraudLogosByOwnerId(913035121393899)
expect(resp).toBe(2)
})
})
class A:
class A {
constructor(tableName, dynamoClient) {
this.dynamoClient = dynamoClient
this.tableName = tableName
}
async getDynamoEntry(query) {
try {
return await this.dynamoClient.query(query).promise()
} catch (error) {
throw error
}
}
async putDynamoEntry(imageEntity) {
try {
return await this.dynamoClient.put({ TableName: this.tableName, Item: imageEntity }).promise()
} catch (error) {
throw error
}
}
async updateDynamoEntry(params) {
try {
return await this.dynamoClient.update(params).promise()
} catch (error) {
throw error
}
}
async deleteDynamoEntry(criteria) {
try {
return await this.dynamoClient.delete(criteria).promise()
} catch (error) {
throw error
}
}
}
module.exports = A
Class B:
const dynamoQueryHelper = require('./DynamoQueryHelper')
const A = require('./A')
class B {
constructor() {
this.A = new A("table1", "client1")
}
async getFraudLogosByOwnerId(ownerId) {
const query = dynamoQueryHelper.getQuery("123", "table1")
try {
return await this.A.getDynamoEntry(query)
} catch (error) {
IPSLogger.logError(
error,
LogConstants.FRAUD_DATA_ACCESS_DAO,
LogConstants.GET_FRAUD_LOGO,
ownerId,
LogConstants.LOG_GET_FRAUD_IMAGE_BY_OWNER_ID.replace(LogConstants.PLACEHOLDER, ownerId)
)
throw error
}
}
}
module.exports = B
I tried the steps given in https://jestjs.io/docs/es6-class-mocks but to no avail
const fs=require('fs')
function add(task1){
var notes=loadNotes()
notes.push({
task:task1
})
saveItems(notes)
}
function saveItems(notes)
{
dataJSON=JSON.stringify(notes)
fs.writeFileSync('notes.json',dataJSON)
}
function loadNotes()
{
try{
data=fs.readFileSync('notes.json')
dataBuffer=data.toString()
finalData=JSON.parse(dataBuffer)
console.log(finalData)
}
catch(e)
{
console.log('emptyList')
return []
}
}
module.exports={
add: add
}
The function "loadNotes" is not returning the list of notes.
function loadNotes()
{
try{
data=fs.readFileSync('notes.json')
dataBuffer=data.toString()
finalData=JSON.parse(dataBuffer)
console.log(finalData)
return finalData;
}
catch(e)
{
console.log('emptyList')
return []
}
}
I keep getting an Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating '_context.t0.response.data'). After doing some digging, it seems like my error is coming from this part of my code. It's the authUser function specifically that seems to be causing the problem
import { addError, removeError } from './error';
import { SET_CURRENT_USER } from '../actionTypes';
import api from '../../services/api';
export const setCurrentUser = user => ({
type: SET_CURRENT_USER,
user
});
export const setToken = token => {
api.setToken(token);
};
export const authUser = (path, data) =>
{
return async dispatch => {
try {
const {token, ...user} = await api.call('post', `auth/${path}`, data);
AsyncStorage.setItem('jwtToken', token);
api.setToken(token);
dispatch(setCurrentUser(user));
dispatch(removeError());
} catch (err) {
const error = err.response.data;
dispatch(addError(error.message));
}
}
};
actionTypes.js
export const SET_CURRENT_USER = 'SET_CURRENT_USER'
api.js
import axios from 'axios';
const host = 'http://localhost:4000/api';
export const setToken = token => {
if (token) {
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
} else {
delete axios.defaults.headers.common['Authorization'];
}
};
export const call = async (method, path, data) => {
const response = await axios[method](`${host}/${path}`, data);
return response.data;
};
export default { setToken, call };
error.js
import {ADD_ERROR, REMOVE_ERROR} from '../actionTypes';
export const addError = error => ({
type: ADD_ERROR,
error
});
export const removeError = () => ({
type: REMOVE_ERROR
});
Error:
Possible Unhandled Promise Rejection (id: 4):
TypeError: undefined is not an object (evaluating '_context.t0.response.data')
_callee$#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:107239:43
tryCatch#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26927:23
invoke#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27103:32
tryCatch#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26927:23
invoke#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27003:30
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27015:21
tryCallOne#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:28865:16
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:28966:27
_callTimer#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32405:17
_callImmediatesPass#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32441:19
callImmediates#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32659:33
callImmediates#[native code]
__callImmediates#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2719:35
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2505:34
__guard#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2702:15
flushedQueue#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2504:21
flushedQueue#[native code]
callFunctionReturnFlushedQueue#[native code]
Also if it helps, I followed the localhost link and the function that is breaking there, tho I did not write this and cannot change it.
var authUser = function authUser(path, data) {
return function _callee(dispatch) {
var _await$api$call, token, user, error;
return _regenerator.default.async(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return _regenerator.default.awrap(_api.default.call('post', "auth/" + path, data));
case 3:
_await$api$call = _context.sent;
token = _await$api$call.token;
user = (0, _objectWithoutProperties2.default)(_await$api$call, ["token"]);
AsyncStorage.setItem('jwtToken', token);
_api.default.setToken(token);
dispatch(setCurrentUser(user));
dispatch((0, _error.removeError)());
_context.next = 16;
break;
case 12:
_context.prev = 12;
_context.t0 = _context["catch"](0);
error = _context.t0.response.data;
dispatch((0, _error.addError)(error.message));
case 16:
case "end":
return _context.stop();
}
}
}, null, null, [[0, 12]], Promise);
};
};
The error is coming from the catch block of the authUser function:
export const authUser = (path, data) =>
{
return async dispatch => {
try {
// ... Other existing codes
} catch (err) {
const error = err.response.data;
dispatch(addError(error.message));
}
}
};
For errors thrown by axios, err.response won't always be available, at times when there is no response from the server or there was a problem making the request in the first place, err.response would be undefined. In such cases, you need to handle other sources of errors. You should update the catch logic to handle the possible error cases, the code should be something like this:
catch (err) {
if (err.response) {
// There is an error response from the server
// You can anticipate error.response.data here
const error = err.response.data;
dispatch(addError(error.message));
} else if (err.request) {
// The request was made but no response was received
// Error details are stored in err.reqeust
console.log(err.request);
} else {
// Some other errors
console.log('Error', err.message);
}
}
More details on handling axios error here.
I keep getting this error when this function executes.
Ignoring exception from a finished function
What I'm I missing?
exports = module.exports = functions.database.ref('/cards/{userId}/{id}')
.onCreate((snap, context) => {
const token = snap.val().token;
const userId = context.params.userId;
const stripeRef = admin.database().ref('/stripe').child(userId);
return stripeRef.once('value').then(function(snapshot) {
let accountId = snapshot.val().accountId;
return stripe.accounts.createExternalAccount(
accountId,
{ external_account: token },
function(err, card) {
snap.ref.child('cardId').set(card.id);
});
});
});
use try and catch to log the errors manually, like
try {
//code goes here
}
catch(error) {
console.log(error)
}
mocha + chai + ts-mockito is executing unit-test of the node.js application.
In order to test the Service class, we mock the method of the Repository class which is called in the Service class.
Running will not work as expected.
I expect ErrorDto, but the string "TypeError: Can not read property 'then' of null" will be returned.
Please tell me something is wrong.
Test code.
let mockedRepository: MyRepository = tsmockito.mock(MyRepository);
describe("MyService Test", () => {
it("getAll() test", async () => {
const errorDto = new ErrorDto();
errorDto.addMessage("test message");
tsmockito.when(mockedRepository.getAll()).thenCall(() => {
return new Promise((resolve, reject) => {
reject(errorDto);
});
});
let mockedRepositoryInstance: MyRepository = tsmockito.instance(mockedRepository);
Container.set(MyRepository, mockedRepositoryInstance);
let service = new MyService();
let res = await service.getAll();
// I expect ErrorDto for res,
// but "TypeError: Can not read property 'then' of null" is returned.
if (res instanceof ErrorDto) {
// Do not reach below
let msg = res.getMessages();
expect(msg[0]).to.eql("test message");
} else {
// Test failure
expect(true).to.false;
}
});
});
Service class to be tested
#Service()
export default class MyService {
#Log()
public getAll() {
const repository = Container.get(MyRepository);
return new Promise<MyServiceTreeDto[]>((resolve, reject) => {
repository.getAll()
.then((res: MyTreeDomain[]) => {
const resDto = new Array<MyServiceTreeDto>();
//do something...
resolve(resDto);
}).catch((err) => {
reject(err);
});
});
}
}
Repository class to be mocked
#Service()
export default class MyRepository {
public async getAll(domain: MyDomain): Promise<MyTreeDomain[]> {
try {
let res: MyTreeDomain[] = new Array<MyTreeDomain>();
//do async process
return res;
} catch (err) {
if (err instanceof ErrorDto) {
throw err;
} else {
const errorDto = new ErrorDto();
errorDto.addMessage("error!");
throw errorDto;
}
}
}
}